From b1cae5c2b75b0bb5c4cbb6b3d76671f6c5050b63 Mon Sep 17 00:00:00 2001 From: king Date: Tue, 1 Sep 2026 10:11:50 +0000 Subject: [PATCH 01/11] ci: migrate legacy CI to GitHub Actions - delete Jenkinsfile (ci-plugin), Jenkinsfile-gitlab, .travis.yml, .gitlab-ci.yml, appveyor.yml - ci_dapps.yml: cover autonomy/bridgevmxgo/evm2/unfreeze/zksync that the Jenkins ci-plugin pipeline used to run (docker-compose-pre.sh run all) - ci_fork_test.yml: port .gitlab-ci.yml fork_test series (schedule + dispatch) - ci_autotest.yml: port make autotest_ci / autotest_tick - README: replace dead travis/appveyor badges with GitHub Actions badge Co-Authored-By: Claude --- .github/workflows/ci_autotest.yml | 65 +++++++++ .github/workflows/ci_dapps.yml | 55 ++++++++ .github/workflows/ci_fork_test.yml | 45 +++++++ .gitlab-ci.yml | 208 ----------------------------- .travis.yml | 74 ---------- Jenkinsfile | 106 --------------- Jenkinsfile-gitlab | 108 --------------- README.md | 7 +- appveyor.yml | 30 ----- 9 files changed, 169 insertions(+), 529 deletions(-) create mode 100644 .github/workflows/ci_autotest.yml create mode 100644 .github/workflows/ci_dapps.yml create mode 100644 .github/workflows/ci_fork_test.yml delete mode 100644 .gitlab-ci.yml delete mode 100644 .travis.yml delete mode 100644 Jenkinsfile delete mode 100644 Jenkinsfile-gitlab delete mode 100644 appveyor.yml diff --git a/.github/workflows/ci_autotest.yml b/.github/workflows/ci_autotest.yml new file mode 100644 index 0000000000..27735d55f9 --- /dev/null +++ b/.github/workflows/ci_autotest.yml @@ -0,0 +1,65 @@ +name: ci_autotest +on: [push, pull_request] + +# 对应 Makefile 的 autotest_ci / autotest_tick: +# autotest_ci -> chain33 build/autotest/jerkinsci 目录,solo 模式跑全量测试用例 +# autotest_tick -> chain33 build/autotest/gitlabci 目录,双节点 + ticket 挖矿场景 +# 两者都是 docker-compose 起链后跑 autotest 二进制,与 build.yml 的 +# `make autotest dapp=all`(local 模式,docker-compose 起 dapp 集群)互补。 + +jobs: + autotest_ci: + name: autotest_ci + runs-on: ubuntu-22.04 + timeout-minutes: 90 + steps: + - name: checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Set up Golang + uses: actions/setup-go@v3 + with: + go-version-file: 'go.mod' + id: go + + - name: set go env + run: export PATH=${PATH}:`go env GOPATH`/bin + + - name: autotest ci + run: | + make build_ci + make autotest_ci + + - name: cleanup + if: always() + run: make clean || true + + autotest_tick: + name: autotest_tick + runs-on: ubuntu-22.04 + timeout-minutes: 90 + steps: + - name: checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Set up Golang + uses: actions/setup-go@v3 + with: + go-version-file: 'go.mod' + id: go + + - name: set go env + run: export PATH=${PATH}:`go env GOPATH`/bin + + - name: autotest tick + run: | + make build_ci + make autotest_tick + + - name: cleanup + if: always() + run: make clean || true diff --git a/.github/workflows/ci_dapps.yml b/.github/workflows/ci_dapps.yml new file mode 100644 index 0000000000..7347af7b63 --- /dev/null +++ b/.github/workflows/ci_dapps.yml @@ -0,0 +1,55 @@ +name: ci_dapps +on: [push, pull_request] + +# 原 Jenkins ci-plugin (Jenkinsfile) 迁移而来。 +# Jenkins 执行 `docker-compose-pre.sh run all`,即遍历 build/ci 下所有 +# 带 testcase.sh 的 dapp 目录;其中 cross2eth/mix/rgbx/rollup 在 Jenkins 里被 +# rm 掉(已有独立 workflow),evm/paracross 也已有独立 workflow。 +# 剩余 5 个 dapp 由本 workflow 接管,逐个并行跑,与 Jenkins 的串行 all 等价。 + +jobs: + ci_dapps: + name: ci_${{ matrix.dapp }} + runs-on: ubuntu-22.04 + timeout-minutes: ${{ matrix.timeout }} + strategy: + # 一个 dapp 失败不影响其他 dapp,便于一次 CI 暴露全部问题 + fail-fast: false + matrix: + include: + - dapp: autonomy + timeout: 60 + - dapp: bridgevmxgo + # ganache(eth+bsc) + 4 个 ebrelayer + 5 个 chain33 节点 + nginx,最重 + timeout: 90 + - dapp: evm2 + timeout: 60 + - dapp: unfreeze + timeout: 60 + - dapp: zksync + timeout: 60 + + steps: + - name: checkout + uses: actions/checkout@v3 + with: + # bridgevmxgo 的 cmd/build.sh 用 git describe --tags 注入版本号 + fetch-depth: 0 + + - name: Set up Golang + uses: actions/setup-go@v3 + with: + go-version-file: 'go.mod' + id: go + + - name: set go env + run: export PATH=${PATH}:`go env GOPATH`/bin + + - name: deploy + run: | + make build_ci + make docker-compose dapp=${{ matrix.dapp }} + + - name: cleanup + if: always() + run: make docker-compose-down dapp=${{ matrix.dapp }} diff --git a/.github/workflows/ci_fork_test.yml b/.github/workflows/ci_fork_test.yml new file mode 100644 index 0000000000..4a16395387 --- /dev/null +++ b/.github/workflows/ci_fork_test.yml @@ -0,0 +1,45 @@ +name: ci_fork_test + +# 原 .gitlab-ci.yml 的 fork_test* 系列迁移而来。 +# GitLab 侧由 onceEveryday 变量 + forkTest 分支控制,只每天跑一次(fork 测试很慢), +# 这里用 schedule + 手动触发等价替代,不挂在 push/pull_request 上。 +# +# 覆盖关系:proj=fork dapp=all 是 GitLab 四个 fork_test 任务的超集 —— +# docker-compose-pre.sh forktest all 会先跑 system-fork-test.sh(对应 fork_test), +# 再遍历所有带 fork-test.sh 的 dapp(目前只有 paracross,对应 fork_test_paracross)。 +# fork_test_privacy 在 GitLab 上本就是空转:privacy 没有 fork-test.sh。 +on: + schedule: + # 每天 18:37 UTC(北京时间次日 02:37)。避开整点,GitHub 官方建议错峰以降低排队延迟 + - cron: '37 18 * * *' + workflow_dispatch: + +jobs: + fork_test: + name: fork_test + runs-on: ubuntu-22.04 + # fork 测试需反复制造分叉并等待链重组收敛,远慢于普通 dapp testcase + timeout-minutes: 120 + steps: + - name: checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Set up Golang + uses: actions/setup-go@v3 + with: + go-version-file: 'go.mod' + id: go + + - name: set go env + run: export PATH=${PATH}:`go env GOPATH`/bin + + - name: fork test + run: | + make build_ci + make fork-test proj=fork dapp=all + + - name: cleanup + if: always() + run: make docker-compose-down proj=fork dapp=all diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml deleted file mode 100644 index 16dfadf734..0000000000 --- a/.gitlab-ci.yml +++ /dev/null @@ -1,208 +0,0 @@ -#image: chain33-build:latest - -before_script: - - export GO_PROJECT_NAMESPACE="$GOPATH/src/gitlab.33.cn/$CI_PROJECT_NAMESPACE" - - echo $GO_PROJECT_NAMESPACE - - mkdir -p $GO_PROJECT_NAMESPACE - - ln -srf $(pwd) $GO_PROJECT_NAMESPACE - - export GO_PROJECT_PATH="$GO_PROJECT_NAMESPACE/$CI_PROJECT_NAME" - - echo $GO_PROJECT_PATH - - cd $GO_PROJECT_PATH - - make clean - -after_script: - - make clean - -stages: - - build - - test - - deploy - - fork_test - - autotest - -go_fmt: - stage: build - tags: - - 33cn - script: - - make checkgofmt - - make fmt - only: - - master - - bty_develop - -go_lint: - stage: build - tags: - - 33cn - script: - - make linter - only: - - master - - bty_develop - -go_test: - stage: test - tags: - - 33cn - script: - - make docker-compose-down dapp=all - - make test - only: - - master - - bty_develop - -#memory_sanitizer: -# stage: test -# script: -# - export CC=clang-5.0 && make msan -# only: -# - master -# - develop -# - bty_develop - - - -#code_coverage_report: -# stage: test -# script: -# - make coverhtml -# only: -# - master -# - develop -# - bty_develop - -deploy: - stage: deploy - tags: - - 33cn - script: - - make build_ci - - make docker-compose - - make docker-compose-down - only: - - master - - bty_develop - -deploy_relay: - stage: deploy - tags: - - 33cn - script: - - make build_ci - - make docker-compose proj=relay dapp=relay - - make docker-compose-down proj=relay dapp=relay - only: - - master - -deploy_paracross: - stage: deploy - tags: - - 33cn - script: - - make build_ci - - make docker-compose proj=paracross dapp=paracross - - make docker-compose-down proj=paracross dapp=paracross - only: - - master - -code_coverage: - stage: fork_test - tags: - - 33cn - script: - - if [ -n "${onceEveryday}" ]; then - - make coverage - - fi - only: - - master - - bty_develop - -fork_test: - stage: fork_test - tags: - - 33cn - script: - - if [ -n "${onceEveryday}" ]; then - - make build_ci - - make fork-test - - make docker-compose-down - - fi - only: - - master - - forkTest - -fork_test_privacy: - stage: fork_test - tags: - - 33cn - script: - - if [ -n "${onceEveryday}" ]; then - - make build_ci - - make fork-test proj=privacy dapp=privacy - - make docker-compose-down proj=privacy dapp=privacy - - fi - only: - - master - - forkTest - -fork_test_paracross: - stage: fork_test - tags: - - 33cn - script: - - if [ -n "${onceEveryday}" ]; then - - make build_ci - - make fork-test proj=paracross dapp=paracross - - make docker-compose-down proj=paracross dapp=paracross - - fi - only: - - master - - forkTest - -##serial run all dapp -fork_test_all: - stage: fork_test - tags: - - 33cn - script: - - if [ -n "${onceEveryday}" ]; then - - make build_ci - - make fork-test proj=fork dapp=all - - make docker-compose-down proj=fork dapp=all - - fi - only: - - master - - forkTest - -##serial run all dapp -deploy_test_all: - stage: fork_test - tags: - - 33cn - script: - - if [ -n "${onceEveryday}" ]; then - - make build_ci - - make docker-compose proj=deploy dapp=all - - make docker-compose-down proj=deploy dapp=all - - fi - only: - - master - - forkTest - - -autotest: - stage: autotest - tags: - - 33cn - script: - - if [ -n "${onceEveryday}" ]; then - - make build_ci - - make autotest - - cd build/tools/autotest && ./run-autotest.sh build - - cd $GO_PROJECT_PATH - - fi - when: always - only: - - master - diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 2152b9b93b..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,74 +0,0 @@ -language: go -go_import_path: github.com/33cn/plugin -os: linux -dist: xenial - -notifications: - email: false -matrix: - include: - - name: check_fmt - sudo: require - go: "1.16.x" - env: - - GO111MODULE=on - install: - - go get -u golang.org/x/tools/cmd/goimports - - go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.18.0 - - go get -u mvdan.cc/sh/cmd/shfmt - - go get -u mvdan.cc/sh/cmd/gosh - script: - - make checkgofmt && make fmt_go - - make linter - - - name: unit-test - go: "1.16.x" - env: - - GO111MODULE=on - install: skip - script: - - make test - - - name: coverage - if: branch = master - go: "1.16.x" - env: - - GO111MODULE=on - before_install: - - go get -t -v ./... - install: skip - script: - - make coverage - after_success: - - bash <(curl -s https://codecov.io/bash) - - - name: auto-test - go: "1.16.x" - env: - - GO111MODULE=on - install: skip - before_script: make build_ci - script: - - make autotest dapp=all - - - name: deploy - if: env(DAPP) IS present - sudo: required - services: - - docker - go: "1.16.x" - env: - - DOCKER_COMPOSE_VERSION=1.21.2 - - GO111MODULE=on - install: - - curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - - - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" - - sudo apt-get update - - sudo apt-get -y -o Dpkg::Options::="--force-confnew" install docker-ce - - sudo rm /usr/local/bin/docker-compose - - curl -L https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-`uname -s`-`uname -m` > docker-compose - - chmod +x docker-compose - - sudo mv docker-compose /usr/local/bin - before_script: make build_ci - script: - - make docker-compose dapp=${DAPP} && make docker-compose-down dapp=${DAPP} && make clean diff --git a/Jenkinsfile b/Jenkinsfile deleted file mode 100644 index 9e4285bcf4..0000000000 --- a/Jenkinsfile +++ /dev/null @@ -1,106 +0,0 @@ - -pipeline { - agent any - - environment { - GOPATH = "${WORKSPACE}" - GO111MODULE = "on" - PROJ_DIR = "${WORKSPACE}/src/github.com/33cn/plugin" - } - - options { - timeout(time: 2,unit: 'HOURS') - retry(1) - timestamps() - gitLabConnection('gitlab33') - gitlabBuilds(builds: ['check']) - checkoutToSubdirectory "src/github.com/33cn/plugin" - } - tools {go 'go'} - stages { - stage('deploy') { - steps { - dir("${PROJ_DIR}"){ - gitlabCommitStatus(name: 'deploy'){ - sh ''' - set -e - go version - make build_ci - cd build - rm -rf "${BUILD_NUMBER}" - mkdir -p "${BUILD_NUMBER}" - cp -r ci/* "${BUILD_NUMBER}/" - ./docker-compose-pre.sh modify - cp chain33* Dockerfile* docker-compose* *.sh "${BUILD_NUMBER}/" - cd "${BUILD_NUMBER}" - rm -rf cross2eth mix rgbx rollup|| true - ./docker-compose-pre.sh run "${BUILD_NUMBER}" all - ''' - } - } - } - - post { - always { - dir("${PROJ_DIR}"){ - sh ''' - set +e - cd build - if [ -d "${BUILD_NUMBER}" ]; then - cd "${BUILD_NUMBER}" - ./docker-compose-pre.sh down "${BUILD_NUMBER}" all || true - cd .. - rm -rf "${BUILD_NUMBER}" - fi - cd .. - make clean || true - ''' - } - } - } - } - } - - post { - always { - echo 'One way or another, I have finished' - // clean up our workspace - deleteDir() - } - - success { - echo 'I succeeeded!' - echo "email user: ${ghprbActualCommitAuthorEmail}" - - script{ - try { - mail to: "${ghprbActualCommitAuthorEmail}", - subject: "Successed Pipeline: ${currentBuild.fullDisplayName}", - body: "this is success with ${env.BUILD_URL}" - } - catch (err){ - echo 'email err' - } - currentBuild.result = 'SUCCESS' - } - echo 'SUCCESS' - - } - - failure { - echo 'I failed ' - echo "email user: ${ghprbActualCommitAuthorEmail}" - script{ - try { - mail to: "${ghprbActualCommitAuthorEmail}", - subject: "Failed Pipeline: ${currentBuild.fullDisplayName}", - body: "Something is wrong with ${env.BUILD_URL}" - }catch (err){ - echo 'email err' - } - } - - echo currentBuild.result - } - } -} diff --git a/Jenkinsfile-gitlab b/Jenkinsfile-gitlab deleted file mode 100644 index 5236ddcadb..0000000000 --- a/Jenkinsfile-gitlab +++ /dev/null @@ -1,108 +0,0 @@ - -pipeline { - agent any - - environment { - GOPATH = "${WORKSPACE}" - GO111MODULE = "on" - PROJ_DIR = "${WORKSPACE}/src/github.com/33cn/plugin" - } - - options { - timeout(time: 2,unit: 'HOURS') - retry(1) - timestamps() - gitLabConnection('gitlab33') - gitlabBuilds(builds: ['check', 'build', 'test', 'deploy']) - checkoutToSubdirectory "src/github.com/33cn/plugin" - } - tools {go 'go1.19'} - stages { - stage('check') { - steps { - dir("${PROJ_DIR}"){ - gitlabCommitStatus(name: 'check'){ - sh "git branch;git status" - sh "make auto_ci branch=${env.gitlabSourceBranch}" - } - } - } - } - - stage('build') { - steps { - dir("${env.PROJ_DIR}"){ - gitlabCommitStatus(name: 'build'){ - sh 'make checkgofmt' - sh 'make linter' - } - } - } - } - - stage('test'){ - agent { - docker{ - image 'suyanlong/chain33-run:latest' - } - } - - environment { - GOPATH = "${WORKSPACE}" - PROJ_DIR = "${WORKSPACE}/src/github.com/33cn/plugin" - } - - steps { - dir("${env.PROJ_DIR}"){ - gitlabCommitStatus(name: 'test'){ - sh 'make test' - //sh 'export CC=clang-5.0 && make msan' - } - } - } - } - - stage('deploy') { - steps { - dir("${PROJ_DIR}"){ - gitlabCommitStatus(name: 'deploy'){ - sh 'make build_ci' - sh "cd build && mkdir ${env.BUILD_NUMBER} && cp ci/* ${env.BUILD_NUMBER} -r && cp chain33* Dockerfile* docker* *.sh ${env.BUILD_NUMBER}/ && cd ${env.BUILD_NUMBER}/ && ./docker-compose-pre.sh run ${env.BUILD_NUMBER} all " - } - } - } - - post { - always { - dir("${PROJ_DIR}"){ - sh "cd build/${env.BUILD_NUMBER} && ./docker-compose-pre.sh down ${env.BUILD_NUMBER} all && cd .. && rm -rf ${env.BUILD_NUMBER} && cd .. && make clean " - } - } - } - } - } - - post { - always { - echo 'One way or another, I have finished' - // clean up our workspace - deleteDir() - } - - success { - echo 'I succeeeded!' - echo "email user: ${gitlabUserEmail}" - mail to: "${gitlabUserEmail}", - subject: "Successed Pipeline: ${currentBuild.fullDisplayName}", - body: "this is success with ${env.BUILD_URL}" - } - - failure { - echo 'I failed ' - echo "email user: ${gitlabUserEmail}" - mail to: "${gitlabUserEmail}", - subject: "Failed Pipeline: ${currentBuild.fullDisplayName}", - body: "Something is wrong with ${env.BUILD_URL}" - } - } -} diff --git a/README.md b/README.md index 895a4c3f14..f78558a7f3 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,8 @@ [![API Reference]( https://camo.githubusercontent.com/915b7be44ada53c290eb157634330494ebe3e30a/68747470733a2f2f676f646f632e6f72672f6769746875622e636f6d2f676f6c616e672f6764646f3f7374617475732e737667 )](https://godoc.org/github.com/33cn/plugin) -[![pipeline status](https://api.travis-ci.org/33cn/plugin.svg?branch=master)](https://travis-ci.org/33cn/plugin/) +[![ci_base](https://github.com/33cn/plugin/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/33cn/plugin/actions/workflows/build.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/33cn/plugin?branch=master)](https://goreportcard.com/report/github.com/33cn/plugin) -[![Windows Build Status](https://ci.appveyor.com/api/projects/status/github/33cn/plugin?svg=true&branch=master&passingText=Windows%20-%20OK&failingText=Windows%20-%20failed&pendingText=Windows%20-%20pending)](https://ci.appveyor.com/project/33cn/plugin) [![codecov](https://codecov.io/gh/33cn/plugin/branch/master/graph/badge.svg)](https://codecov.io/gh/33cn/plugin) # chain33 官方插件系统(v1.71.1) @@ -85,4 +84,6 @@ make push b=branch_dev_name m="hello world" 在build目录下写testcase和相关的Dockerfile和docker-compose配置文件, testcase的规则参考plugin/dapp/testcase_compose_rule.md -用户可以在travis自己工程里面设置自己plugin的DAPP变量,如DAPP设置为relay,则travis里面run relay的testcase +CI 全部由 GitHub Actions 驱动(`.github/workflows/`)。新增 dapp 的 testcase 后, +在 `.github/workflows/ci_dapps.yml` 的 matrix 里加一行 `- dapp: ` 即可, +本地可用 `make docker-compose dapp=` 复现,`make docker-compose-down dapp=` 清理。 diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 73d3751c9c..0000000000 --- a/appveyor.yml +++ /dev/null @@ -1,30 +0,0 @@ -version: "{build}" - - -#init: -# - git config --global core.autocrlf input - -# Build - -os: Visual Studio 2019 - -build: off - -clone_folder: c:\gopath\src\github.com\33cn\plugin - -environment: - GOPATH: c:\gopath - - -# set go version -before_test: - - set PATH=C:\go122\bin;%PATH% - - set GOROOT=C:\go122 - - go version - - go env - - -test_script: - - build.bat -# - for /f "" %%G in ('go list github.com/33cn/plugin/...') do ( go test %%G & IF ERRORLEVEL == 1 EXIT 1) - From de4bec552dc094715bf9de81bf7050d72c9adcf6 Mon Sep 17 00:00:00 2001 From: king Date: Tue, 1 Sep 2026 10:11:59 +0000 Subject: [PATCH 02/11] ci: fix golinter.sh silent no-op and dead linters - --skip-dirs=[...] unquoted: golangci-lint treats skip-dirs as a regex, so the bracket was parsed as a character class matching nearly every path, silently skipping the whole repo (bug present since 2020, which is why make linter always passed while 440+ files were unformatted) - res=$(...) captured only stdout, swallowing golangci-lint errors from stderr and faking a pass on configuration errors - drop deprecated linters deadcode/interfacer/varcheck/structcheck/golint (deprecated in golangci-lint v1.38-v1.49, no-ops in v1.53.3) - add --max-issues-per-linter=0/--max-same-issues=0 so findings are not silently truncated at the default caps - make linter: gate shellcheck at -S warning (note/info findings like SC2004/SC2317 do not fail CI) Co-Authored-By: Claude --- Makefile | 3 ++- golinter.sh | 66 ++++++++++++++++++++++++++--------------------------- 2 files changed, 35 insertions(+), 34 deletions(-) diff --git a/Makefile b/Makefile index a3b5c8d92d..779a8a3599 100644 --- a/Makefile +++ b/Makefile @@ -122,7 +122,8 @@ dep: linter: vet ineffassign ## Use gometalinter check code, ignore some unserious warning @./golinter.sh "filter" - @find . -name '*.sh' -not -path "./vendor/*" | xargs shellcheck -e SC2086 + # -S warning:note/info 级(数组下标 $ 冗余 SC2004、间接调用 unreachable SC2317 等)不阻断 CI + @find . -name '*.sh' -not -path "./vendor/*" | xargs shellcheck -e SC2086 -S warning linter_test: ## Use gometalinter check code, for local test @./golinter.sh "test" "${p}" diff --git a/golinter.sh b/golinter.sh index 22b16ec952..53e5b17abe 100755 --- a/golinter.sh +++ b/golinter.sh @@ -5,45 +5,45 @@ set +e OP="${1}" path="${2}" +# 启用的 linter 集合。注意:原先还启用了 deadcode/interfacer/varcheck/structcheck/golint, +# 这 5 个在 golangci-lint v1.38~v1.49 间先后废弃,v1.53.3 只打 deprecation 警告并跳过, +# 属于死配置,故移除。如需补回等价能力:deadcode/varcheck/structcheck -> unused, +# golint -> revive,interfacer 无替代(作者已归档)。 +LINTERS=( + --enable=gofmt + --enable=gosimple + --enable=unconvert + --enable=goimports + --enable=misspell +) + +# 必须加引号:不加引号时 bash 把 [..] 当 glob,且 golangci-lint 将 skip-dirs 按正则处理, +# 字符类 [plugin/dapp/...] 会匹配几乎所有路径,导致全仓被跳过、lint 静默空转。 +SKIP_DIRS='plugin/dapp/evm/executor/vm/common/crypto' + function filterLinter() { - res=$( - golangci-lint run --no-config --issues-exit-code=0 --deadline=2m --disable-all \ - --enable=gofmt \ - --enable=gosimple \ - --enable=deadcode \ - --enable=unconvert \ - --enable=interfacer \ - --enable=varcheck \ - --enable=structcheck \ - --enable=goimports \ - --enable=misspell \ - --enable=golint \ - --skip-dirs=["plugin/dapp/evm/executor/vm/common/crypto"] \ - --exclude=underscores \ - --exclude-use-default=false - ) - if [[ ${#res} -gt "0" ]]; then - echo -e "${res}" - exit 1 - fi + # 不用 res=$(...) 捕获后判断长度:那样只收 stdout,golangci-lint 自身的报错走 stderr + # 会被丢弃,配置错误时会伪装成"检查通过"。这里直接用退出码。 + golangci-lint run --no-config --issues-exit-code=1 --timeout=20m --disable-all \ + "${LINTERS[@]}" \ + --max-issues-per-linter=0 \ + --max-same-issues=0 \ + --skip-dirs="${SKIP_DIRS}" \ + --exclude=underscores \ + --exclude-use-default=false \ + ./... } function testLinter() { cd "${path}" >/dev/null || exit - golangci-lint run --no-config --issues-exit-code=1 --deadline=2m --disable-all \ - --enable=gofmt \ - --enable=gosimple \ - --enable=deadcode \ - --enable=unconvert \ - --enable=interfacer \ - --enable=varcheck \ - --enable=structcheck \ - --enable=goimports \ - --enable=misspell \ - --enable=golint \ + golangci-lint run --no-config --issues-exit-code=1 --timeout=20m --disable-all \ + "${LINTERS[@]}" \ --enable=nolintlint \ - --skip-dirs=["plugin/dapp/evm/executor/vm/common/crypto"] \ - --exclude=underscores + --max-issues-per-linter=0 \ + --max-same-issues=0 \ + --skip-dirs="${SKIP_DIRS}" \ + --exclude=underscores \ + ./... cd - >/dev/null || exit } From 816dc79e0ad1b89f3b862b151e1046f64c3dcd10 Mon Sep 17 00:00:00 2001 From: king Date: Tue, 1 Sep 2026 10:13:33 +0000 Subject: [PATCH 03/11] style: gofmt -s and goimports across the repo, plus gosimple/unconvert/misspell fixes - gofmt -s: mostly Go 1.19+ doc comment reformatting (//foo -> // foo), import grouping, and a few for-range simplifications (no semantics) - goimports: import order - gosimple: for-range over channel/select, copy() vs loop, append(slice...), fmt.Printf vs Println(Sprintf), drop redundant returns and bool compares, type-switch with bound variable, redundant map delete guards - unconvert: drop redundant type conversions (verified identical types) - misspell: fix typos in CLI help, log and error strings - ineffassign: discard results that are never read; add missing err checks in rgbx query/exec tests - verified: go vet, go build, make linter all pass Co-Authored-By: Claude --- plugin/consensus/dpos/consensus_state.go | 10 +- plugin/consensus/dpos/dpos.go | 2 +- plugin/consensus/dpos/node.go | 2 +- plugin/consensus/dpos/peer_set.go | 2 +- plugin/consensus/dpos/types/dpos_msg.pb.go | 2 + .../dpos/types/priv_validator_test.go | 4 +- plugin/consensus/para/kv.go | 2 +- plugin/consensus/para/para.go | 8 +- plugin/consensus/para/paraP2pProc.go | 2 +- plugin/consensus/para/parablssign.go | 14 +- plugin/consensus/para/paracreate.go | 13 +- plugin/consensus/para/parajumpdownload.go | 20 +- plugin/consensus/para/paramultidownload.go | 4 +- plugin/consensus/para/paraquery.go | 2 +- plugin/consensus/para/parasync_test.go | 36 ++-- plugin/consensus/pbft/block.go | 2 +- plugin/consensus/qbft/consensus_state.go | 6 +- plugin/consensus/qbft/node.go | 2 +- plugin/consensus/qbft/peer_set.go | 32 ++- plugin/consensus/qbft/qbft.go | 2 +- plugin/consensus/qbft/store.go | 2 +- plugin/consensus/qbft/types/block.go | 2 +- plugin/consensus/qbft/types/const.go | 2 +- plugin/consensus/qbft/types/validator_set.go | 4 +- plugin/consensus/qbft/types/vote_set.go | 14 +- plugin/consensus/raft/block.go | 4 +- plugin/consensus/raft/raft.go | 4 +- .../consensus/tendermint/consensus_state.go | 10 +- plugin/consensus/tendermint/node.go | 2 +- plugin/consensus/tendermint/peer_set.go | 3 +- plugin/consensus/tendermint/store.go | 2 +- plugin/consensus/tendermint/tendermint.go | 2 +- plugin/consensus/tendermint/tools/nonePerf.go | 2 +- plugin/consensus/tendermint/types/block.go | 2 +- plugin/consensus/tendermint/types/const.go | 2 +- .../tendermint/types/validator_set.go | 4 +- plugin/consensus/tendermint/types/vote_set.go | 14 +- plugin/consensus/ticket/ticket.go | 4 +- plugin/consensus/ticket/ticket_test.go | 3 +- plugin/crypto/bls/bls.go | 8 +- plugin/crypto/bls/bls_test.go | 2 +- .../accountmanager/executor/account_test.go | 2 +- .../dapp/accountmanager/executor/accountdb.go | 18 +- .../accountmanager/executor/accountmanager.go | 8 +- .../accountmanager/executor/exec_local.go | 12 +- plugin/dapp/accountmanager/executor/query.go | 10 +- plugin/dapp/accountmanager/executor/tables.go | 14 +- .../accountmanager/types/accountmanager.go | 12 +- .../accountmanager/types/accountmanager.pb.go | 12 +- plugin/dapp/autonomy/executor/autonomy.go | 2 +- plugin/dapp/autonomy/executor/boardaction.go | 8 +- plugin/dapp/autonomy/executor/boardtable.go | 12 +- plugin/dapp/autonomy/executor/changeaction.go | 6 +- plugin/dapp/autonomy/executor/changetable.go | 12 +- plugin/dapp/autonomy/executor/itemtable.go | 12 +- plugin/dapp/autonomy/executor/projecttable.go | 12 +- .../dapp/autonomy/executor/ruleaction_test.go | 10 +- plugin/dapp/autonomy/executor/ruletable.go | 12 +- plugin/dapp/autonomy/types/const.go | 6 +- plugin/dapp/autonomy/types/lcommon.pb.go | 2 +- plugin/dapp/autonomy/types/types.go | 4 +- plugin/dapp/blackwhite/executor/blackwhite.go | 2 +- plugin/dapp/blackwhite/types/types.go | 4 +- .../boss4x/chain33/offline/createERC20.go | 2 +- .../chain33/offline/deployCrossX2Chain33.go | 6 +- .../boss4x/chain33/offline/multisignSetup.go | 2 +- .../chain33/offline/multisignTransfer.go | 2 +- plugin/dapp/cert/authority/authority_test.go | 35 ++-- .../tools/cryptogen/factory/csp/fileks.go | 10 +- plugin/dapp/cert/executor/cert.go | 6 +- plugin/dapp/cert/types/types.go | 6 +- plugin/dapp/coinsx/commands/coinsx.go | 2 +- plugin/dapp/coinsx/executor/action.go | 7 +- plugin/dapp/coinsx/executor/coinsx.go | 2 +- plugin/dapp/coinsx/types/coinsx.pb.go | 2 +- plugin/dapp/coinsx/types/types.go | 2 +- plugin/dapp/collateralize/commands/cmd.go | 28 +-- .../collateralize/executor/collateralize.go | 2 +- .../collateralize/executor/collateralizedb.go | 8 +- plugin/dapp/collateralize/executor/query.go | 20 +- .../dapp/collateralize/types/collateralize.go | 4 +- plugin/dapp/collateralize/types/table.go | 22 +-- plugin/dapp/collateralize/types/types.go | 8 +- .../boss4x/chain33/offline/createERC20.go | 2 +- .../chain33/offline/deployCrossX2Chain33.go | 4 +- .../chain33/offline/multisignTransfer.go | 2 +- .../boss4x/chain33/offline/offline.go | 1 - .../boss4x/ethereum/offline/cfgLockedToken.go | 2 +- .../ethereum/offline/deployCrossX2Eth.go | 20 +- .../boss4x/ethereum/offline/offline.go | 1 - .../ethereum/offline/safeTransferCmd.go | 2 +- .../contracts/test/bridgeBank_test.go | 32 +-- .../contracts/test/setup/setupTestEnv.go | 16 +- .../dapp/cross2eth/ebcli/chain33RelayerCmd.go | 24 +-- .../cross2eth/ebcli/ethereumRelayerCmd.go | 79 ++++---- plugin/dapp/cross2eth/ebcli/main.go | 2 +- .../dapp/cross2eth/ebcli/mulsign4chain33.go | 1 - plugin/dapp/cross2eth/ebcli/statics.go | 6 +- plugin/dapp/cross2eth/ebrelayer/main.go | 26 ++- .../ebrelayer/relayer/chain33/chain33.go | 6 +- .../ebrelayer/relayer/chain33/store.go | 8 +- .../relayer/chain33/transceiver/sync/proc.go | 14 +- .../chain33/transceiver/sync/pubilc_sync.go | 2 +- .../transceiver/sync/sync_tx_receipts.go | 23 +-- .../cross2eth/ebrelayer/relayer/chain33/tx.go | 11 +- .../ebrelayer/relayer/ethereum/account.go | 14 +- .../ebrelayer/relayer/ethereum/ethereum.go | 17 +- .../ebrelayer/relayer/ethereum/ethtxs/abi.go | 4 +- .../relayer/ethereum/ethtxs/auxiliary.go | 12 +- .../relayer/ethereum/ethtxs/deploy.go | 10 +- .../relayer/ethereum/ethtxs/ethtxs_test.go | 12 +- .../relayer/ethereum/ethtxs/parser.go | 2 +- .../relayer/ethereum/ethtxs/queryFromEth.go | 16 +- .../relayer/ethereum/ethtxs/recover.go | 4 +- .../ethereum/ethtxs/relayToEthereum.go | 2 +- .../relayer/ethereum/ethtxs/types.go | 2 +- .../relayer/ethereum/ethtxs/utils.go | 12 +- .../ebrelayer/relayer/ethereum/store.go | 4 +- .../ebrelayer/relayer/events/ethereumEvent.go | 4 +- .../cross2eth/ebrelayer/relayer/manager.go | 52 ++--- plugin/dapp/cross2eth/ebrelayer/types/info.go | 2 +- .../cross2eth/ebrelayer/types/relayer.pb.go | 7 +- .../dapp/cross2eth/ebrelayer/utils/solsha3.go | 6 +- .../dapp/cross2eth/ebrelayer/utils/utils.go | 28 +-- .../cross2eth/ebrelayer/version/version.go | 4 +- .../dex/boss/deploy/chain33/offline/common.go | 2 +- .../dex/boss/deploy/ethereum/cakeHandler.go | 6 +- .../dapp/dex/boss/deploy/ethereum/ethCli.go | 6 +- .../dapp/dex/boss/deploy/ethereum/farmCmd.go | 4 +- .../dex/boss/deploy/ethereum/farmHandler.go | 2 +- .../ethereum/offline/deployContractCmd.go | 8 +- .../boss/deploy/ethereum/offline/poolCmd.go | 6 +- .../dex/boss/deploy/ethereum/offline/query.go | 1 - plugin/dapp/dposvote/commands/vote.go | 4 +- plugin/dapp/dposvote/executor/dposvote.go | 10 +- plugin/dapp/dposvote/executor/dposvotedb.go | 60 +++--- .../dapp/dposvote/executor/exec_del_local.go | 18 +- plugin/dapp/dposvote/executor/exec_local.go | 18 +- plugin/dapp/dposvote/executor/query.go | 22 +-- plugin/dapp/dposvote/types/const.go | 10 +- plugin/dapp/dposvote/types/msg.go | 4 +- plugin/dapp/dposvote/types/table.go | 60 +++--- plugin/dapp/dposvote/types/types.go | 4 +- plugin/dapp/echo/types/echo/echo.pb.go | 2 + plugin/dapp/echo/types/echo/types.go | 4 +- plugin/dapp/evm/commands/evm.go | 16 +- plugin/dapp/evm/executor/abi/abi_test.go | 34 ++-- plugin/dapp/evm/executor/abi/api.go | 2 +- plugin/dapp/evm/executor/abi/reflect.go | 10 +- .../evm/executor/attack_integration_test.go | 2 +- plugin/dapp/evm/executor/query_test.go | 26 +-- plugin/dapp/evm/executor/vm/common/address.go | 2 +- plugin/dapp/evm/executor/vm/common/big.go | 9 +- .../crypto/bn256/cloudflare/constants.go | 1 + .../crypto/bn256/cloudflare/example_test.go | 1 + .../dapp/evm/executor/vm/common/math/big.go | 8 +- plugin/dapp/evm/executor/vm/gas/gas.go | 3 +- .../dapp/evm/executor/vm/mm/memory_table.go | 30 +-- .../dapp/evm/executor/vm/runtime/contracts.go | 9 +- .../evm/executor/vm/runtime/contracts_test.go | 2 +- .../executor/vm/runtime/customizeContracts.go | 8 +- plugin/dapp/evm/executor/vm/runtime/evm.go | 4 +- .../evm/executor/vm/runtime/instructions.go | 4 +- plugin/dapp/evm/executor/vm/runtime/logger.go | 2 +- plugin/dapp/evm/executor/vm/runtime/token.go | 8 +- plugin/dapp/evm/executor/vm/state/statedb.go | 12 +- plugin/dapp/evm/types/evmcontract.pb.go | 2 +- plugin/dapp/evmxgo/executor/exec_local.go | 2 +- plugin/dapp/evmxgo/executor/kv.go | 2 +- plugin/dapp/evmxgo/executor/parse.go | 4 +- plugin/dapp/exchange/client/exchange.go | 2 +- plugin/dapp/exchange/client/grpc_cli.go | 2 +- plugin/dapp/exchange/executor/exchange.go | 6 +- .../dapp/exchange/executor/exchange_test.go | 2 +- plugin/dapp/exchange/executor/exchangedb.go | 64 +++--- plugin/dapp/exchange/executor/exec_local.go | 2 +- plugin/dapp/exchange/executor/query.go | 10 +- plugin/dapp/exchange/executor/tables.go | 40 ++-- plugin/dapp/exchange/test/client.go | 2 +- plugin/dapp/exchange/test/cmd/main.go | 2 +- plugin/dapp/exchange/test/exchange_test.go | 8 +- plugin/dapp/exchange/test/exec_cli.go | 12 +- plugin/dapp/exchange/test/grpc_cli.go | 12 +- plugin/dapp/exchange/types/exchange.go | 8 +- plugin/dapp/exchange/types/exchange.pb.go | 30 +-- plugin/dapp/exchange/types/exchangecfg.go | 2 +- plugin/dapp/game/executor/game.go | 2 +- plugin/dapp/game/executor/gamedb.go | 6 +- plugin/dapp/game/types/const.go | 8 +- plugin/dapp/game/types/types.go | 12 +- plugin/dapp/guess/commands/game.go | 14 +- plugin/dapp/guess/executor/exec.go | 10 +- plugin/dapp/guess/executor/exec_del_local.go | 8 +- plugin/dapp/guess/executor/exec_local.go | 10 +- plugin/dapp/guess/executor/guess.go | 10 +- plugin/dapp/guess/executor/guessdb.go | 46 ++--- plugin/dapp/guess/executor/query.go | 16 +- plugin/dapp/guess/rpc/guess_test.go | 14 +- plugin/dapp/guess/types/const.go | 10 +- plugin/dapp/guess/types/table.go | 24 +-- plugin/dapp/guess/types/types.go | 4 +- plugin/dapp/hashlock/executor/hashlock.go | 2 +- .../hashlock/executor/hashlock_unit_test.go | 2 +- plugin/dapp/hashlock/types/hashlock.go | 4 +- plugin/dapp/issuance/commands/cmd.go | 22 +-- plugin/dapp/issuance/executor/issuance.go | 2 +- plugin/dapp/issuance/executor/issuancedb.go | 2 +- plugin/dapp/issuance/executor/query.go | 16 +- plugin/dapp/issuance/types/issuance.go | 4 +- plugin/dapp/issuance/types/table.go | 22 +-- plugin/dapp/issuance/types/types.go | 10 +- plugin/dapp/js/command/js.go | 4 +- plugin/dapp/js/executor/account.go | 17 +- plugin/dapp/js/executor/js.go | 8 +- plugin/dapp/js/executor/jsvm_test.go | 2 +- plugin/dapp/js/executor/runtime.go | 2 +- plugin/dapp/js/executor/table.go | 14 +- plugin/dapp/js/types/js.go | 20 +- .../lightclient/lighttypes/lightclient.pb.go | 5 +- .../rpc/lightclient/neutrino/tss.go | 2 +- plugin/dapp/lottery/executor/lottery.go | 2 +- plugin/dapp/lottery/executor/lotterydb.go | 2 +- plugin/dapp/lottery/types/lottery.go | 4 +- plugin/dapp/lottery/types/types.go | 4 +- plugin/dapp/mix/commands/mix.go | 8 +- plugin/dapp/mix/executor/committree.go | 14 +- plugin/dapp/mix/executor/committree_test.go | 2 +- plugin/dapp/mix/executor/exec.go | 6 +- plugin/dapp/mix/executor/exec_del_local.go | 8 +- plugin/dapp/mix/executor/exec_local.go | 8 +- plugin/dapp/mix/executor/kv.go | 2 +- plugin/dapp/mix/executor/merkletree/tree.go | 6 +- .../dapp/mix/executor/merkletree/tree_test.go | 2 +- plugin/dapp/mix/executor/merkletree/verify.go | 5 +- plugin/dapp/mix/executor/mix.go | 6 +- plugin/dapp/mix/executor/mixtxtable.go | 12 +- plugin/dapp/mix/executor/transfer.go | 4 +- plugin/dapp/mix/executor/util.go | 2 +- plugin/dapp/mix/rpc/rpc.go | 3 +- plugin/dapp/mix/types/authorize.go | 2 +- plugin/dapp/mix/types/cryptokey.pb.go | 8 +- plugin/dapp/mix/types/deposit.go | 4 +- plugin/dapp/mix/types/merkletree.pb.go | 8 +- plugin/dapp/mix/types/mix.go | 4 +- plugin/dapp/mix/types/mix.pb.go | 8 +- plugin/dapp/mix/types/mixwallet.pb.go | 10 +- plugin/dapp/mix/types/transferInput.go | 2 +- plugin/dapp/mix/types/transferOutput.go | 2 +- plugin/dapp/mix/types/type.go | 4 +- plugin/dapp/mix/types/withdraw.go | 2 +- plugin/dapp/mix/wallet/exec.go | 2 +- plugin/dapp/mix/wallet/mix.go | 5 +- plugin/dapp/mix/wallet/mixbizdb.go | 3 +- plugin/dapp/mix/wallet/mixbiztable.go | 12 +- plugin/dapp/mix/wallet/mixstore.go | 9 +- plugin/dapp/mix/wallet/txtransfer.go | 3 +- plugin/dapp/mix/wallet/txwithdraw.go | 1 - plugin/dapp/mix/wallet/util.go | 4 +- plugin/dapp/mix/wallet/util_test.go | 1 - plugin/dapp/multisig/commands/multisig.go | 30 +-- plugin/dapp/multisig/executor/exec.go | 12 +- .../dapp/multisig/executor/exec_del_local.go | 12 +- plugin/dapp/multisig/executor/exec_local.go | 12 +- plugin/dapp/multisig/executor/exec_test.go | 20 +- plugin/dapp/multisig/executor/kv.go | 31 +-- plugin/dapp/multisig/executor/multisig.go | 48 ++--- plugin/dapp/multisig/executor/multisigdb.go | 34 ++-- plugin/dapp/multisig/executor/query.go | 182 ++++++++++-------- plugin/dapp/multisig/rpc/jrpc_channel_test.go | 4 +- plugin/dapp/multisig/rpc/rpc_real_test.go | 24 +-- plugin/dapp/multisig/types/const.go | 12 +- plugin/dapp/multisig/types/errors.go | 2 +- plugin/dapp/multisig/types/multisig.pb.go | 62 +++--- plugin/dapp/multisig/types/types.go | 16 +- plugin/dapp/multisig/wallet/exec.go | 2 +- plugin/dapp/multisig/wallet/exec_test.go | 12 +- plugin/dapp/multisig/wallet/multisig.go | 18 +- plugin/dapp/multisig/wallet/multisig_store.go | 4 +- plugin/dapp/norm/executor/norm.go | 2 +- plugin/dapp/norm/types/const.go | 2 +- plugin/dapp/norm/types/norm.go | 4 +- plugin/dapp/oracle/executor/oracle.go | 2 +- plugin/dapp/oracle/executor/query.go | 8 +- plugin/dapp/oracle/types/oracle.pb.go | 2 +- plugin/dapp/oracle/types/table.go | 12 +- plugin/dapp/oracle/types/types.go | 4 +- plugin/dapp/paracross/commands/paracross.go | 8 +- plugin/dapp/paracross/executor/account.go | 4 +- plugin/dapp/paracross/executor/action.go | 44 ++--- plugin/dapp/paracross/executor/asset.go | 50 ++--- plugin/dapp/paracross/executor/bindminer.go | 2 +- plugin/dapp/paracross/executor/db.go | 4 +- plugin/dapp/paracross/executor/exec.go | 26 +-- .../dapp/paracross/executor/exec_del_local.go | 18 +- plugin/dapp/paracross/executor/exec_local.go | 26 +-- plugin/dapp/paracross/executor/filtertxs.go | 30 +-- plugin/dapp/paracross/executor/kv.go | 16 +- plugin/dapp/paracross/executor/miner.go | 6 +- .../paracross/executor/minerrewards/nomal.go | 4 +- plugin/dapp/paracross/executor/paracross.go | 10 +- plugin/dapp/paracross/executor/query.go | 28 +-- plugin/dapp/paracross/executor/reward.go | 6 +- .../dapp/paracross/executor/rollupcrosstx.go | 8 +- plugin/dapp/paracross/executor/stage.go | 2 +- plugin/dapp/paracross/executor/stagetable.go | 12 +- .../paracross/executor/superaccount_test.go | 2 +- .../paracross/executor/supervisionaccount.go | 2 +- plugin/dapp/paracross/testnode/cfg.go | 2 +- plugin/dapp/paracross/testnode/paranode.go | 6 +- plugin/dapp/paracross/types/parabls.pb.go | 2 +- plugin/dapp/paracross/types/paracross.go | 20 +- plugin/dapp/paracross/types/paracross.pb.go | 4 +- plugin/dapp/paracross/types/paraminer.pb.go | 6 +- plugin/dapp/paracross/types/type.go | 4 +- plugin/dapp/paracross/wallet/para.go | 2 +- plugin/dapp/pokerbull/executor/pokerbull.go | 2 +- plugin/dapp/pokerbull/executor/pokerbulldb.go | 4 +- plugin/dapp/pokerbull/types/const.go | 8 +- plugin/dapp/pokerbull/types/pokerbull.pb.go | 24 +-- plugin/dapp/pokerbull/types/types.go | 4 +- .../dapp/privacy/autotest/createutxosCase.go | 4 +- .../dapp/privacy/autotest/privToPrivCase.go | 2 +- plugin/dapp/privacy/autotest/privToPubCase.go | 2 +- plugin/dapp/privacy/autotest/pubToPriv.go | 2 +- plugin/dapp/privacy/commands/privacy.go | 2 +- plugin/dapp/privacy/crypto/privacy.go | 7 +- plugin/dapp/privacy/executor/kv.go | 10 +- plugin/dapp/privacy/executor/privacy.go | 12 +- plugin/dapp/privacy/types/const.go | 4 +- plugin/dapp/privacy/types/privacy.go | 4 +- plugin/dapp/privacy/types/privacy.pb.go | 6 +- plugin/dapp/privacy/wallet/keys.go | 18 +- plugin/dapp/privacy/wallet/privacy.go | 9 +- plugin/dapp/privacy/wallet/privacystore.go | 26 +-- plugin/dapp/privacy/wallet/util.go | 10 +- plugin/dapp/qbftNode/commands/qbftNode.go | 2 +- plugin/dapp/qbftNode/executor/qbftNode.go | 2 +- plugin/dapp/qbftNode/types/qbftNode.go | 4 +- plugin/dapp/relay/executor/relay.go | 2 +- plugin/dapp/relay/executor/relay_test.go | 8 +- plugin/dapp/relay/executor/relaydb_test.go | 12 +- plugin/dapp/relay/types/relay.go | 8 +- plugin/dapp/relay/types/relay.pb.go | 2 +- plugin/dapp/retrieve/executor/retrieve.go | 4 +- .../retrieve/executor/retrieve_unit_test.go | 2 +- plugin/dapp/retrieve/types/const.go | 2 +- plugin/dapp/retrieve/types/types.go | 4 +- plugin/dapp/rgbx/commands/commands.go | 1 + plugin/dapp/rgbx/executor/exec_local_test.go | 1 + plugin/dapp/rgbx/executor/query_test.go | 6 +- plugin/dapp/rgbx/types/address.go | 3 +- plugin/dapp/rgbx/types/rgbx.pb.go | 5 +- plugin/dapp/rollup/executor/exec_local.go | 2 +- plugin/dapp/storage/crypto/aes.go | 8 +- plugin/dapp/storage/crypto/aes_test.go | 2 +- plugin/dapp/storage/crypto/crypto.go | 10 +- plugin/dapp/storage/crypto/des.go | 16 +- plugin/dapp/storage/crypto/des_test.go | 4 +- plugin/dapp/storage/executor/exec_local.go | 2 +- plugin/dapp/storage/executor/query.go | 4 +- plugin/dapp/storage/executor/storage.go | 2 +- plugin/dapp/storage/executor/storage_test.go | 2 +- plugin/dapp/storage/executor/storagedb.go | 24 +-- plugin/dapp/storage/types/storage.go | 8 +- plugin/dapp/storage/types/storage.pb.go | 8 +- plugin/dapp/ticket/executor/ticket.go | 2 +- plugin/dapp/ticket/types/ticket.go | 6 +- plugin/dapp/ticket/wallet/keys.go | 2 +- plugin/dapp/ticket/wallet/ticketstore.go | 2 +- .../signatory-server/signatory/config.pb.go | 2 + plugin/dapp/token/executor/kv.go | 2 +- plugin/dapp/token/executor/token.go | 2 +- plugin/dapp/token/executor/token_new_test.go | 2 +- plugin/dapp/token/rpc/rpc.go | 2 +- plugin/dapp/token/types/token.pb.go | 2 +- plugin/dapp/token/types/types.go | 4 +- plugin/dapp/trade/executor/local_order.go | 15 +- plugin/dapp/trade/executor/local_order_v2.go | 8 +- plugin/dapp/trade/executor/trade.go | 2 +- plugin/dapp/trade/executor/tradedb.go | 4 +- plugin/dapp/trade/executor/util.go | 2 +- plugin/dapp/trade/rpc/jrpc.go | 12 +- plugin/dapp/trade/rpc/rpc.go | 12 +- plugin/dapp/trade/rpc/types.go | 8 +- plugin/dapp/trade/types/const.go | 8 +- plugin/dapp/trade/types/trade.go | 34 ++-- plugin/dapp/trade/types/trade.pb.go | 5 +- plugin/dapp/trade/types/tx.go | 12 +- plugin/dapp/unfreeze/executor/unfreeze.go | 2 +- plugin/dapp/valnode/commands/valnode.go | 2 +- plugin/dapp/valnode/executor/valnode.go | 2 +- plugin/dapp/valnode/types/valnode.go | 4 +- plugin/dapp/vote/executor/exec_local.go | 4 +- plugin/dapp/vote/executor/table.go | 24 +-- plugin/dapp/vote/types/vote.pb.go | 10 +- plugin/dapp/wasm/executor/callback.go | 6 +- .../x2ethereum/commands/buildflags/flags.go | 2 +- plugin/dapp/x2ethereum/commands/commands.go | 14 +- .../x2ethereum/ebcli/chain33RelayerCmd.go | 8 +- .../x2ethereum/ebcli/ethereumRelayerCmd.go | 104 +++++----- plugin/dapp/x2ethereum/ebcli/main.go | 2 +- plugin/dapp/x2ethereum/ebcli/statics.go | 14 +- .../ethcontract/test/setup/setupTestEnv.go | 6 +- .../dapp/x2ethereum/ebrelayer/ethtxs/abi.go | 4 +- .../x2ethereum/ebrelayer/ethtxs/auxiliary.go | 20 +- .../x2ethereum/ebrelayer/ethtxs/deploy.go | 22 +-- .../x2ethereum/ebrelayer/ethtxs/parser.go | 2 +- .../ebrelayer/ethtxs/queryFromEth.go | 14 +- .../x2ethereum/ebrelayer/ethtxs/recover.go | 4 +- .../ebrelayer/ethtxs/relayToChain33.go | 5 +- .../ebrelayer/ethtxs/relayToEthereum.go | 2 +- .../dapp/x2ethereum/ebrelayer/ethtxs/types.go | 2 +- .../ebrelayer/events/ethereumEvent.go | 4 +- .../x2ethereum/ebrelayer/events/events.go | 2 +- plugin/dapp/x2ethereum/ebrelayer/main.go | 18 +- .../ebrelayer/relayer/chain33/account.go | 10 +- .../ebrelayer/relayer/chain33/chain33.go | 4 +- .../ebrelayer/relayer/chain33/store.go | 4 +- .../relayer/chain33/transceiver/sync/proc.go | 14 +- .../chain33/transceiver/sync/pubilc_sync.go | 2 +- .../transceiver/sync/sync_tx_receipts.go | 10 +- .../ebrelayer/relayer/ethereum/account.go | 16 +- .../ebrelayer/relayer/ethereum/ethereum.go | 52 ++--- .../ebrelayer/relayer/ethereum/store.go | 6 +- .../x2ethereum/ebrelayer/relayer/manager.go | 84 ++++---- .../x2ethereum/ebrelayer/types/config.pb.go | 2 + .../dapp/x2ethereum/ebrelayer/types/info.go | 4 +- .../x2ethereum/ebrelayer/types/relayer.pb.go | 5 +- .../dapp/x2ethereum/ebrelayer/utils/utils.go | 14 +- plugin/dapp/x2ethereum/executor/exec.go | 6 +- plugin/dapp/x2ethereum/executor/exec_local.go | 2 +- plugin/dapp/x2ethereum/executor/prophecy.go | 12 +- .../x2ethereum/executor/x2ethereumaction.go | 6 +- .../dapp/x2ethereum/executor/x2ethereumdb.go | 30 +-- plugin/dapp/x2ethereum/types/const.go | 10 +- plugin/dapp/x2ethereum/types/errors.go | 4 +- plugin/dapp/x2ethereum/types/kv.go | 20 +- plugin/dapp/x2ethereum/types/utils.go | 14 +- plugin/dapp/x2ethereum/types/x2ethereum.go | 6 +- plugin/dapp/zksync/commands/commands.go | 2 +- .../dapp/zksync/commands/l2txs/fetchBlock.go | 4 +- .../dapp/zksync/commands/l2txs/setPubKey.go | 2 +- plugin/dapp/zksync/commands/l2txs/utils.go | 2 +- plugin/dapp/zksync/commands/proof.go | 68 ++++--- plugin/dapp/zksync/executor/accountTree.go | 6 +- plugin/dapp/zksync/executor/exec_local.go | 6 +- plugin/dapp/zksync/executor/kv.go | 52 ++--- plugin/dapp/zksync/executor/tables.go | 26 +-- plugin/dapp/zksync/executor/util.go | 16 +- plugin/dapp/zksync/executor/zkproofhistory.go | 14 +- plugin/dapp/zksync/executor/zkproofutil.go | 6 +- .../dapp/zksync/executor/zkproofutil_test.go | 2 +- plugin/dapp/zksync/executor/zksync.go | 8 +- plugin/dapp/zksync/executor/zksyncOption.go | 54 +++--- plugin/dapp/zksync/types/witness.pb.go | 6 +- plugin/dapp/zksync/types/zksync.go | 14 +- plugin/dapp/zksync/types/zksync.pb.go | 24 +-- plugin/dapp/zksync/wallet/utils.go | 14 +- plugin/mempool/para/base.go | 6 +- plugin/mempool/para/mempool.go | 2 +- plugin/mempool/price/cache.go | 6 +- plugin/mempool/price/mempool.go | 2 +- plugin/mempool/score/cache.go | 2 +- plugin/mempool/score/mempool.go | 2 +- plugin/p2p/gossip/addrbook.go | 8 +- plugin/p2p/gossip/common.go | 4 +- plugin/p2p/gossip/const.go | 2 +- plugin/p2p/gossip/downloadblocks.go | 8 +- plugin/p2p/gossip/monitor.go | 72 ++++--- plugin/p2p/gossip/nat/nat.go | 12 +- plugin/p2p/gossip/node.go | 2 +- plugin/p2p/gossip/p2p.go | 6 +- plugin/p2p/gossip/p2p_test.go | 10 +- plugin/p2p/gossip/p2pserver.go | 4 +- plugin/p2p/gossip/process.go | 4 +- plugin/p2p/gossip/tls.go | 13 +- plugin/p2p/gossip/version.go | 2 +- plugin/store/kvmvcc/kvmvccdb_test.go | 8 +- plugin/store/kvmvccmavl/kvmvcc_mavl.go | 4 +- plugin/store/kvmvccmavl/kvmvcc_mavl_test.go | 8 +- plugin/store/kvmvccmavl/kvmvccdb.go | 12 +- plugin/store/mpt/db/database.go | 2 +- plugin/store/mpt/db2/rlp/decode.go | 12 +- plugin/store/mpt/mpt_test.go | 2 +- version/version.go | 4 +- 485 files changed, 2469 insertions(+), 2444 deletions(-) diff --git a/plugin/consensus/dpos/consensus_state.go b/plugin/consensus/dpos/consensus_state.go index a30e753c1b..85c518766a 100644 --- a/plugin/consensus/dpos/consensus_state.go +++ b/plugin/consensus/dpos/consensus_state.go @@ -139,11 +139,11 @@ func (cs *ConsensusState) IsRunning() bool { return atomic.LoadUint32(&cs.started) == 1 && atomic.LoadUint32(&cs.stopped) == 0 } -//---------------------------------------- +// ---------------------------------------- // String returns a string. func (cs *ConsensusState) String() string { // better not to access shared variables - return fmt.Sprintf("ConsensusState") //(H:%v R:%v S:%v", cs.Height, cs.Round, cs.Step) + return "ConsensusState" //(H:%v R:%v S:%v", cs.Height, cs.Round, cs.Step) } // GetValidatorMgr returns a copy of the ValidatorMgr. @@ -429,11 +429,7 @@ func (cs *ConsensusState) CheckVotes() (ty int, vote *dpostype.VoteItem) { voteStat := map[string]int{} for i := 0; i < len(cs.dposVotes); i++ { key := string(cs.dposVotes[i].VoteItem.VoteID) - if _, ok := voteStat[key]; ok { - voteStat[key]++ - } else { - voteStat[key] = 1 - } + voteStat[key]++ } key := "" diff --git a/plugin/consensus/dpos/dpos.go b/plugin/consensus/dpos/dpos.go index a3517d09ef..ac93bb5031 100644 --- a/plugin/consensus/dpos/dpos.go +++ b/plugin/consensus/dpos/dpos.go @@ -785,7 +785,7 @@ func (client *Client) GetNode() *Node { return client.node } -//CmpBestBlock 比较newBlock是不是最优区块 +// CmpBestBlock 比较newBlock是不是最优区块 func (client *Client) CmpBestBlock(newBlock *types.Block, cmpBlock *types.Block) bool { return false } diff --git a/plugin/consensus/dpos/node.go b/plugin/consensus/dpos/node.go index a7ee219e99..52757ceb18 100644 --- a/plugin/consensus/dpos/node.go +++ b/plugin/consensus/dpos/node.go @@ -594,7 +594,7 @@ func (node *Node) reconnectToPeer(addr string) { dposlog.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start)) } -//--------------------------------------------------------------------- +// --------------------------------------------------------------------- func randomSleep(interval time.Duration) { r := time.Duration(ttypes.RandInt63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond time.Sleep(r + interval) diff --git a/plugin/consensus/dpos/peer_set.go b/plugin/consensus/dpos/peer_set.go index 21a94d5833..dec90c7f16 100644 --- a/plugin/consensus/dpos/peer_set.go +++ b/plugin/consensus/dpos/peer_set.go @@ -202,7 +202,7 @@ func (ps *PeerSet) Remove(peer Peer) { delete(ps.lookup, peer.ID()) } -//-------------------------peer connection-------------------------------- +// -------------------------peer connection-------------------------------- func (pc *peerConn) ID() ID { if len(pc.id) != 0 { return pc.id diff --git a/plugin/consensus/dpos/types/dpos_msg.pb.go b/plugin/consensus/dpos/types/dpos_msg.pb.go index 1f2961e526..6f99f36374 100644 --- a/plugin/consensus/dpos/types/dpos_msg.pb.go +++ b/plugin/consensus/dpos/types/dpos_msg.pb.go @@ -5,9 +5,11 @@ Package types is a generated protocol buffer package. It is generated from these files: + dpos_msg.proto It has these top-level messages: + CycleBoundaryInfo SuperNode VoteItem diff --git a/plugin/consensus/dpos/types/priv_validator_test.go b/plugin/consensus/dpos/types/priv_validator_test.go index f2902aca9e..46bad1069e 100644 --- a/plugin/consensus/dpos/types/priv_validator_test.go +++ b/plugin/consensus/dpos/types/priv_validator_test.go @@ -336,13 +336,13 @@ func TestPubkeyAndAddress(t *testing.T) { func testOneKey(priv, pub, addr string, t *testing.T) { tmp, _ := hex.DecodeString(priv) bPriv, _ := ConsensusCrypto.PrivKeyFromBytes(tmp) - fmt.Println(fmt.Sprintf("%x", bPriv)) + fmt.Printf("%x\n", bPriv) bPub, _ := PubKeyFromString(pub) assert.True(t, bytes.Equal(bPub.Bytes(), bPriv.PubKey().Bytes())) bAddr := address.BytesToBtcAddress(address.NormalVer, bPub.Bytes()).Hash160[:] fmt.Println("addr:", addr) - fmt.Println(fmt.Sprintf("%x", bAddr)) + fmt.Printf("%x\n", bAddr) assert.True(t, addr == fmt.Sprintf("%X", bAddr)) } diff --git a/plugin/consensus/para/kv.go b/plugin/consensus/para/kv.go index 1ef4b1a6e5..c0b0446cf0 100644 --- a/plugin/consensus/para/kv.go +++ b/plugin/consensus/para/kv.go @@ -14,7 +14,7 @@ func calcTitleHeightKey(title string, height int64) []byte { return []byte(fmt.Sprintf("%s-TH-%s-%d", types.ConsensusParaTxsPrefix, title, height)) } -//temp main height tx data for big size +// temp main height tx data for big size func calcTitleMainHeightKey(title string, height int64) []byte { return []byte(fmt.Sprintf("%s-TMH-%s-%d", types.ConsensusParaTxsPrefix, title, height)) } diff --git a/plugin/consensus/para/para.go b/plugin/consensus/para/para.go index 8a28545821..2f8b51fd16 100644 --- a/plugin/consensus/para/para.go +++ b/plugin/consensus/para/para.go @@ -101,7 +101,7 @@ func New(cfg *types.Consensus, sub []byte) queue.Module { } //支持创世精度为0 if subcfg.GenesisAmount < 0 { - panic(fmt.Sprintf("genesis amount <0")) + panic("genesis amount <0") } if subcfg.WriteBlockMsec <= 0 { @@ -172,7 +172,7 @@ func New(cfg *types.Consensus, sub []byte) queue.Module { return para } -//para 不检查任何的交易 +// para 不检查任何的交易 func (client *client) CheckBlock(parent *types.Block, current *types.BlockDetail) error { err := checkMinerTx(current) return err @@ -397,12 +397,12 @@ func checkMinerTx(current *types.BlockDetail) error { return nil } -//比较newBlock是不是最优区块 +// 比较newBlock是不是最优区块 func (client *client) CmpBestBlock(newBlock *types.Block, cmpBlock *types.Block) bool { return false } -//["0:50","100:20","500:30"] +// ["0:50","100:20","500:30"] func parseEmptyBlockInterval(cfg []string) ([]*emptyBlockInterval, error) { var emptyInter []*emptyBlockInterval if len(cfg) == 0 { diff --git a/plugin/consensus/para/paraP2pProc.go b/plugin/consensus/para/paraP2pProc.go index ec41f3963e..b2c80c4466 100644 --- a/plugin/consensus/para/paraP2pProc.go +++ b/plugin/consensus/para/paraP2pProc.go @@ -9,7 +9,7 @@ import ( "github.com/pkg/errors" ) -//新增需要保证顺序 +// 新增需要保证顺序 const ( P2pSubCommitTx = 1 P2pSubLeaderSyncMsg = 2 diff --git a/plugin/consensus/para/parablssign.go b/plugin/consensus/para/parablssign.go index ecbe62b9bf..5dd2bdf5f0 100644 --- a/plugin/consensus/para/parablssign.go +++ b/plugin/consensus/para/parablssign.go @@ -176,7 +176,7 @@ out: } } -//处理leader sync tx, 需接受同步的数据,两个节点基本的共识高度相同, 两个共同leader需相同 +// 处理leader sync tx, 需接受同步的数据,两个节点基本的共识高度相同, 两个共同leader需相同 func (b *blsClient) rcvLeaderSyncTx(sync *pt.LeaderSyncInfo) error { nodes, _, base, off, isLeader, _ := b.getLeaderInfo() if len(nodes) <= 0 { @@ -281,7 +281,7 @@ func (b *blsClient) clearDonePool(consensHeight int64) { } } -//1. 要等到达成共识了才发送,不然处理未达成共识的各种场景会比较复杂,而且浪费手续费 +// 1. 要等到达成共识了才发送,不然处理未达成共识的各种场景会比较复杂,而且浪费手续费 func (b *blsClient) procAggregateTxs() { defer b.paraClient.wg.Done() if len(b.selfID) <= 0 || !b.blsSignOn { @@ -402,7 +402,7 @@ func hasCommited(addrs []string, addr string) (bool, int) { return false, 0 } -//整合相同高度commits +// 整合相同高度commits func integrateCommits(pool map[int64]*pt.ParaBlsSignSumDetails, commits []*pt.ParacrossCommitAction) { for _, cmt := range commits { if _, ok := pool[cmt.Status.Height]; !ok { @@ -422,7 +422,7 @@ func integrateCommits(pool map[int64]*pt.ParaBlsSignSumDetails, commits []*pt.Pa } } -//txBuff中任一高度满足done则认为ok,有可能某些未达成的高度是冗余的,达成共识的高度发给链最终判决 +// txBuff中任一高度满足done则认为ok,有可能某些未达成的高度是冗余的,达成共识的高度发给链最终判决 func isMostCommitDone(nodes int, txsBuff map[int64]*pt.ParaBlsSignSumDetails, isLeader bool, leader string) bool { if nodes <= 0 { return false @@ -439,7 +439,7 @@ func isMostCommitDone(nodes int, txsBuff map[int64]*pt.ParaBlsSignSumDetails, is return false } -//找出共识并达到2/3的commits, 并去除与共识不同的commits,为后面聚合签名做准备 +// 找出共识并达到2/3的commits, 并去除与共识不同的commits,为后面聚合签名做准备 func filterDoneCommits(nodes int, pool map[int64]*pt.ParaBlsSignSumDetails) []*pt.ParaBlsSignSumDetails { var seq []int64 for i, v := range pool { @@ -481,7 +481,7 @@ func filterDoneCommits(nodes int, pool map[int64]*pt.ParaBlsSignSumDetails) []*p } -//聚合多个签名为一个签名,并设置地址bitmap +// 聚合多个签名为一个签名,并设置地址bitmap func (b *blsClient) aggregateCommit2Action(nodes []string, commits []*pt.ParaBlsSignSumDetails) ([]*pt.ParacrossCommitAction, error) { var notify []*pt.ParacrossCommitAction for _, v := range commits { @@ -543,7 +543,7 @@ func (b *blsClient) getBlsPriKey(key []byte) crypto.PrivKey { } } -//transfer secp256 Private key to bls pub key +// transfer secp256 Private key to bls pub key func (b *blsClient) secp256Prikey2BlsPub(key string) (string, error) { secpPrkKey, err := getSecpPriKey(key) if err != nil { diff --git a/plugin/consensus/para/paracreate.go b/plugin/consensus/para/paracreate.go index 18cec3ca3a..545fcaf402 100644 --- a/plugin/consensus/para/paracreate.go +++ b/plugin/consensus/para/paracreate.go @@ -70,7 +70,7 @@ func (client *client) getLocalBlockSeq(height int64) (int64, []byte, error) { } -//根据匹配上的chainblock,设置当前localdb block +// 根据匹配上的chainblock,设置当前localdb block func (client *client) alignLocalBlock2ChainBlock(chainBlock *types.Block) error { localBlock := &pt.ParaLocalDbBlock{ Height: chainBlock.Height, @@ -83,8 +83,8 @@ func (client *client) alignLocalBlock2ChainBlock(chainBlock *types.Block) error } -//如果localBlock被删除了,就从chain block获取,如果block能获取到,但远程seq获取不到,则返回当前块主链hash和错误的seq=0, -//然后请求交易校验不过会进入循环匹配切换场景 +// 如果localBlock被删除了,就从chain block获取,如果block能获取到,但远程seq获取不到,则返回当前块主链hash和错误的seq=0, +// 然后请求交易校验不过会进入循环匹配切换场景 func (client *client) getLastLocalBlockSeq() (int64, []byte, error) { height, err := client.getLastLocalHeight() if err == nil { @@ -119,7 +119,7 @@ func (client *client) getLastLocalBlock() (*pt.ParaLocalDbBlock, error) { return client.getLocalBlockByHeight(height) } -//genesis block scenario +// genesis block scenario func (client *client) syncFromGenesisBlock() (int64, *types.Block, error) { lastSeq, lastBlock, err := client.getLastBlockMainInfo() if err != nil { @@ -200,7 +200,6 @@ func (client *client) switchHashMatchedBlock() (int64, []byte, error) { return mainSeq, localBlock.MainHash, nil } -// func (client *client) switchLocalHashMatchedBlock() (int64, *pt.ParaLocalDbBlock, error) { lastBlock, err := client.getLastLocalBlock() if err != nil { @@ -326,7 +325,7 @@ func validMainBlocks(txs *types.ParaTxDetails) *types.ParaTxDetails { return txs } -//主链blockchain支持按过滤平行链交易后,此接口弃用 +// 主链blockchain支持按过滤平行链交易后,此接口弃用 func (client *client) requestTxsFromBlock(currSeq int64, preMainBlockHash []byte) (*types.ParaTxDetails, error) { cfg := client.GetAPI().GetConfig() blockSeq, err := client.GetBlockOnMainBySeq(currSeq) @@ -477,7 +476,7 @@ func (client *client) procLocalAddBlock(mainBlock *types.ParaTxDetail, lastBlock } -//只同步只有AddType的block,比如在当前高度1w高度前的主链blocks,默认没有分叉,只获取addType类型的,如果有分叉,也会在后面常规同步时候纠正过来 +// 只同步只有AddType的block,比如在当前高度1w高度前的主链blocks,默认没有分叉,只获取addType类型的,如果有分叉,也会在后面常规同步时候纠正过来 func (client *client) procLocalAddBlocks(mainBlocks *types.ParaTxDetails) error { var blocks []*pt.ParaLocalDbBlock lastBlock, err := client.getLastLocalBlock() diff --git a/plugin/consensus/para/parajumpdownload.go b/plugin/consensus/para/parajumpdownload.go index a80a86f797..aefa5181d8 100644 --- a/plugin/consensus/para/parajumpdownload.go +++ b/plugin/consensus/para/parajumpdownload.go @@ -32,7 +32,7 @@ func newJumpDldCli(para *client, cfg *subConfig) *jumpDldClient { return &jumpDldClient{paraClient: para} } -//校验按高度获取的block hash和前一步对应高度的blockhash比对 +// 校验按高度获取的block hash和前一步对应高度的blockhash比对 func verifyBlockHash(heights []*types.BlockInfo, blocks []*types.ParaTxDetail) error { heightMap := make(map[int64][]byte) for _, h := range heights { @@ -81,7 +81,7 @@ func (j *jumpDldClient) getParaHeightList(startHeight, endHeight int64) ([]*type } } -//把不连续的平行链区块高度按offset分成二维数组,方便后面处理 +// 把不连续的平行链区块高度按offset分成二维数组,方便后面处理 func splitHeights2Rows(heights []*types.BlockInfo, offset int) [][]*types.BlockInfo { var ret [][]*types.BlockInfo for i := 0; i < len(heights); i += offset { @@ -94,8 +94,8 @@ func splitHeights2Rows(heights []*types.BlockInfo, offset int) [][]*types.BlockI return ret } -//按高度每次获取实际1000个有平行链交易的区块,这些区块并不一定连续,为了连续处理有交易和没有交易的区块,需要特殊设置起始结束高度, -//但每次处理的起始高度和结束高度都包含了有交易的1000个平行链高度 +// 按高度每次获取实际1000个有平行链交易的区块,这些区块并不一定连续,为了连续处理有交易和没有交易的区块,需要特殊设置起始结束高度, +// 但每次处理的起始高度和结束高度都包含了有交易的1000个平行链高度 func getHeaderStartEndRange(startHeight, endHeight int64, arr [][]*types.BlockInfo, i int) (int64, int64) { single := arr[i] s := startHeight @@ -185,7 +185,7 @@ func (j *jumpDldClient) processTxJobs(ch chan *paraTxBlocksJob) { } } -//按高度list请求平行链区块,服务器有可能返回少于请求高度,少于时候需要继续请求 +// 按高度list请求平行链区块,服务器有可能返回少于请求高度,少于时候需要继续请求 func (j *jumpDldClient) fetchHeightListBlocks(hlist []int64, title string) (*types.ParaTxDetails, error) { index := 0 retBlocks := &types.ParaTxDetails{} @@ -272,7 +272,7 @@ func (j *jumpDldClient) procParaTxHeaders(startHeight, endHeight int64, paraBloc return nil } -//每1000header执行一次比全部获取出来更有效率,可以和同步层更好并行处理,节约时间,1000paraTxBlocks花时间很少,相比headers获取,串行获取时间可以忽略 +// 每1000header执行一次比全部获取出来更有效率,可以和同步层更好并行处理,节约时间,1000paraTxBlocks花时间很少,相比headers获取,串行获取时间可以忽略 func (j *jumpDldClient) getParaTxs(startHeight, endHeight int64, heights []*types.BlockInfo, jobCh chan *paraTxBlocksJob) error { title := j.paraClient.GetAPI().GetConfig().GetTitle() heightsRows := splitHeights2Rows(heights, int(types.MaxBlockCountPerTime)) @@ -302,10 +302,10 @@ func (j *jumpDldClient) getParaTxs(startHeight, endHeight int64, heights []*type return nil } -//Jump Download 是选择有平行链交易的区块跳跃下载的功能,分为三个步骤: -//0. 只获取当前主链高度1w高度前的区块,默认没有分叉,都是addType block -//1. 获取所有平行链交易的高度列表,大概5s以内 -//2. 按高度列表获取含平行链交易的主链区块每次获取一段1000高度,并获取相关范围的主链headers,一起执行,单独获取headers和同步处理不能并行 +// Jump Download 是选择有平行链交易的区块跳跃下载的功能,分为三个步骤: +// 0. 只获取当前主链高度1w高度前的区块,默认没有分叉,都是addType block +// 1. 获取所有平行链交易的高度列表,大概5s以内 +// 2. 按高度列表获取含平行链交易的主链区块每次获取一段1000高度,并获取相关范围的主链headers,一起执行,单独获取headers和同步处理不能并行 func (j *jumpDldClient) tryJumpDownload() { curMainHeight, err := j.paraClient.GetLastHeightOnMainChain() if err != nil { diff --git a/plugin/consensus/para/paramultidownload.go b/plugin/consensus/para/paramultidownload.go index 8829f19496..4067235b88 100644 --- a/plugin/consensus/para/paramultidownload.go +++ b/plugin/consensus/para/paramultidownload.go @@ -33,7 +33,7 @@ type connectCli struct { timeout uint32 } -//invertory 是每次请求的最小单位,每次请求最多MaxBlockCountPerTime +// invertory 是每次请求的最小单位,每次请求最多MaxBlockCountPerTime type inventory struct { start int64 end int64 @@ -177,7 +177,7 @@ func (m *multiDldClient) getConns(inv *inventory) error { return nil } -//缺省不打开,因为有些节点下载时间不稳定,容易超时出错,后面看怎么优化 +// 缺省不打开,因为有些节点下载时间不稳定,容易超时出错,后面看怎么优化 func (m *multiDldClient) tryMultiServerDownload() { curMainHeight, err := m.paraClient.GetLastHeightOnMainChain() if err != nil { diff --git a/plugin/consensus/para/paraquery.go b/plugin/consensus/para/paraquery.go index ca3ada082e..79b288c286 100644 --- a/plugin/consensus/para/paraquery.go +++ b/plugin/consensus/para/paraquery.go @@ -13,7 +13,7 @@ import ( pt "github.com/33cn/plugin/plugin/dapp/paracross/types" ) -//IsCaughtUp 是否追上最新高度, +// IsCaughtUp 是否追上最新高度, func (client *client) Query_IsCaughtUp(req *types.ReqNil) (types.Message, error) { if client == nil { return nil, fmt.Errorf("%s", "client not bind message queue.") diff --git a/plugin/consensus/para/parasync_test.go b/plugin/consensus/para/parasync_test.go index 3869e4b85c..98443fcae6 100644 --- a/plugin/consensus/para/parasync_test.go +++ b/plugin/consensus/para/parasync_test.go @@ -40,12 +40,12 @@ var ( actionReturnIndexAtom int32 ) -//测试初始化 +// 测试初始化 func initTestSyncBlock() { //println("initSyncBlock") } -//新建一个para测试实例并初始化一些参数 +// 新建一个para测试实例并初始化一些参数 func createParaTestInstance(t *testing.T, q queue.Queue) *client { para := new(client) para.subCfg = new(subConfig) @@ -83,7 +83,7 @@ func createParaTestInstance(t *testing.T, q queue.Queue) *client { return para } -//生成创世区块测试数据 +// 生成创世区块测试数据 func makeGenesisBlockInputTestData() *types.Block { newBlock := &types.Block{} newBlock.Height = 0 @@ -95,7 +95,7 @@ func makeGenesisBlockInputTestData() *types.Block { return newBlock } -//生成创世区块响应测试数据 +// 生成创世区块响应测试数据 func makeGenesisBlockReplyTestData(testLoopCount int32) interface{} { switch testLoopCount { case 0: @@ -105,9 +105,9 @@ func makeGenesisBlockReplyTestData(testLoopCount int32) interface{} { } } -//生成getNextAction不同返回情况下的同步测试数据 -//index 对应getNextAction的每一步返回顺序,按return的先后顺序索引 -//testLoopCount 测试轮数 +// 生成getNextAction不同返回情况下的同步测试数据 +// index 对应getNextAction的每一步返回顺序,按return的先后顺序索引 +// testLoopCount 测试轮数 func makeSyncReplyTestData(index int32, testLoopCount int32) ( interface{}, //*types.Block, //GetLastBlock reply interface{}, //*types.LocalReplyValue, //GetLastLocalHeight reply @@ -181,7 +181,7 @@ func makeSyncReplyTestData(index int32, testLoopCount int32) ( } } -//生成清理功能Get Reply测试数据 +// 生成清理功能Get Reply测试数据 func makeCleanDataGetReplyTestData(clearLocalDBCallCount int32, testLoopCount int32) interface{} { switch clearLocalDBCallCount { case 1: //testinitFirstLocalHeightIfNeed会调用到 @@ -213,7 +213,7 @@ func makeCleanDataGetReplyTestData(clearLocalDBCallCount int32, testLoopCount in } } -//生成清理功能Set Reply测试数据 +// 生成清理功能Set Reply测试数据 func makeCleanDataSetReplyTestData(testLoopCount int32) interface{} { reply := &types.Reply{} reply.IsOk = testLoopCount == 0 @@ -221,7 +221,7 @@ func makeCleanDataSetReplyTestData(testLoopCount int32) interface{} { return reply } -//mock queue Message 返回 +// mock queue Message 返回 func mockMessageReply(q queue.Queue) { blockChainKey := "blockchain" @@ -334,7 +334,7 @@ func mockMessageReply(q queue.Queue) { } } -//测试创世区块写入 +// 测试创世区块写入 func testCreateGenesisBlock(t *testing.T, para *client, testLoopCount int32) { genesisBlock := makeGenesisBlockInputTestData() err := para.blockSyncClient.createGenesisBlock(genesisBlock) @@ -348,7 +348,7 @@ func testCreateGenesisBlock(t *testing.T, para *client, testLoopCount int32) { } -//测试清理localdb缓存数据 +// 测试清理localdb缓存数据 func testClearLocalOldBlocks(t *testing.T, para *client, testLoopCount int32) { err := para.blockSyncClient.clearLocalOldBlocks() @@ -362,7 +362,7 @@ func testClearLocalOldBlocks(t *testing.T, para *client, testLoopCount int32) { } } -//测试初始化开始高度 +// 测试初始化开始高度 func testInitFirstLocalHeightIfNeed(t *testing.T, para *client, testLoopCount int32) { err := para.blockSyncClient.initFirstLocalHeightIfNeed() @@ -374,7 +374,7 @@ func testInitFirstLocalHeightIfNeed(t *testing.T, para *client, testLoopCount in } } -//测试一次区块同步操作 +// 测试一次区块同步操作 func testSyncBlocksIfNeed(t *testing.T, para *client, testLoopCount int32) { errorCount := int32(0) for i := int32(1); i <= 10; i++ { @@ -396,7 +396,7 @@ func testSyncBlocksIfNeed(t *testing.T, para *client, testLoopCount int32) { atomic.StoreInt32(&actionReturnIndexAtom, 0) } -//测试SyncHasCaughtUp +// 测试SyncHasCaughtUp func testSyncHasCaughtUp(t *testing.T, para *client, testLoopCount int32) { oldValue := para.blockSyncClient.syncHasCaughtUp() para.blockSyncClient.setSyncCaughtUp(true) @@ -406,7 +406,7 @@ func testSyncHasCaughtUp(t *testing.T, para *client, testLoopCount int32) { assert.Equal(t, true, isSyncHasCaughtUp) } -//测试getBlockSyncState +// 测试getBlockSyncState func testGetBlockSyncState(t *testing.T, para *client, testLoopCount int32) { oldValue := para.blockSyncClient.getBlockSyncState() para.blockSyncClient.setBlockSyncState(blockSyncStateFinished) @@ -416,7 +416,7 @@ func testGetBlockSyncState(t *testing.T, para *client, testLoopCount int32) { assert.Equal(t, true, syncState == blockSyncStateFinished) } -//执行所有函数测试 +// 执行所有函数测试 func execTest(t *testing.T, para *client, testLoopCount int32) { atomic.StoreInt32(&actionReturnIndexAtom, 0) atomic.StoreInt32(&testLoopCountAtom, testLoopCount) @@ -430,7 +430,7 @@ func execTest(t *testing.T, para *client, testLoopCount int32) { testGetBlockSyncState(t, para, testLoopCount) } -//测试入口 +// 测试入口 func TestSyncBlocks(t *testing.T) { cfg := types.NewChain33Config(testnode.DefaultConfig) q := queue.New("channel") diff --git a/plugin/consensus/pbft/block.go b/plugin/consensus/pbft/block.go index 6eb5aec59c..e20b82d8c5 100644 --- a/plugin/consensus/pbft/block.go +++ b/plugin/consensus/pbft/block.go @@ -147,7 +147,7 @@ func (client *Client) readReply() { } -//CmpBestBlock 比较newBlock是不是最优区块 +// CmpBestBlock 比较newBlock是不是最优区块 func (client *Client) CmpBestBlock(newBlock *types.Block, cmpBlock *types.Block) bool { return false } diff --git a/plugin/consensus/qbft/consensus_state.go b/plugin/consensus/qbft/consensus_state.go index 6cd18b424b..5991c2de8c 100644 --- a/plugin/consensus/qbft/consensus_state.go +++ b/plugin/consensus/qbft/consensus_state.go @@ -588,7 +588,7 @@ func (cs *ConsensusState) handleTxsAvailable(height int64) { switch cs.Step { case ttypes.RoundStepNewHeight: // timeoutCommit phase // +1ms to ensure RoundStepNewRound timeout always happens after RoundStepNewHeight - timeoutCommit := cs.StartTime.Sub(time.Now()) + 1*time.Millisecond + timeoutCommit := time.Until(cs.StartTime) + 1*time.Millisecond cs.scheduleTimeout(timeoutCommit, height, round, ttypes.RoundStepNewRound) case ttypes.RoundStepNewRound: // after timeoutCommit cs.enterPropose(height, round) @@ -600,7 +600,9 @@ func (cs *ConsensusState) handleTxsAvailable(height int64) { // Used internally by handleTimeout and handleMsg to make state transitions // Enter: `timeoutNewHeight` by startTime (commitTime+timeoutCommit), -// or, if SkipTimeout==true, after receiving all precommits from (height,round-1) +// +// or, if SkipTimeout==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) diff --git a/plugin/consensus/qbft/node.go b/plugin/consensus/qbft/node.go index 064392ffbf..ce0bd1e50b 100644 --- a/plugin/consensus/qbft/node.go +++ b/plugin/consensus/qbft/node.go @@ -604,7 +604,7 @@ func (node *Node) reconnectToPeer(addr string) { qbftlog.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start)) } -//--------------------------------------------------------------------- +// --------------------------------------------------------------------- func randomSleep(interval time.Duration) { r := time.Duration(ttypes.RandInt63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond time.Sleep(r + interval) diff --git a/plugin/consensus/qbft/peer_set.go b/plugin/consensus/qbft/peer_set.go index 259210fc29..35f682bc81 100644 --- a/plugin/consensus/qbft/peer_set.go +++ b/plugin/consensus/qbft/peer_set.go @@ -227,7 +227,7 @@ func (ps *PeerSet) Remove(peer Peer) { delete(ps.lookup, peer.ID()) } -//-------------------------peer connection-------------------------------- +// -------------------------peer connection-------------------------------- func (pc *peerConn) ID() ID { if len(pc.id) != 0 { return pc.id @@ -519,23 +519,19 @@ func decodeMsg(msg []byte, cmp byte) ([]byte, error) { } func (pc *peerConn) sendRoutine() { -FOR_LOOP: - for { - select { - case msg := <-pc.sendQueue: - raw := encodeMsg(msg.Msg, msg.TypeID) - _, err := pc.bufWriter.Write(raw) - if err != nil { - qbftlog.Error("sendRoutine buffer write fail", "peer", pc, "err", err) - pc.stopForError(err) - break FOR_LOOP - } - err = pc.bufWriter.Flush() - if err != nil { - qbftlog.Error("sendRoutine buffer flush fail", "peer", pc, "err", err) - pc.stopForError(err) - break FOR_LOOP - } + for msg := range pc.sendQueue { + raw := encodeMsg(msg.Msg, msg.TypeID) + _, err := pc.bufWriter.Write(raw) + if err != nil { + qbftlog.Error("sendRoutine buffer write fail", "peer", pc, "err", err) + pc.stopForError(err) + break + } + err = pc.bufWriter.Flush() + if err != nil { + qbftlog.Error("sendRoutine buffer flush fail", "peer", pc, "err", err) + pc.stopForError(err) + break } } qbftlog.Info("peerConn stop sendRoutine", "peerIP", pc.ip.String()) diff --git a/plugin/consensus/qbft/qbft.go b/plugin/consensus/qbft/qbft.go index db49728534..4569d42176 100644 --- a/plugin/consensus/qbft/qbft.go +++ b/plugin/consensus/qbft/qbft.go @@ -711,7 +711,7 @@ func (client *Client) Query_NodeInfo(req *types.ReqNil) (types.Message, error) { if val == nil { nodes = append(nodes, &tmtypes.QbftNodeInfo{}) } else { - ipstr, idstr := "UNKOWN", "UNKOWN" + ipstr, idstr := "UNKNOWN", "UNKNOWN" pub, err := ttypes.ConsensusCrypto.PubKeyFromBytes(val.PubKey) if err != nil { qbftlog.Error("Query_NodeInfo invalid pubkey", "err", err) diff --git a/plugin/consensus/qbft/store.go b/plugin/consensus/qbft/store.go index c04b880704..479c06f702 100644 --- a/plugin/consensus/qbft/store.go +++ b/plugin/consensus/qbft/store.go @@ -17,7 +17,7 @@ var ( stateKey = []byte("stateKey") ) -//ConsensusStore ... +// ConsensusStore ... type ConsensusStore struct { db dbm.DB } diff --git a/plugin/consensus/qbft/types/block.go b/plugin/consensus/qbft/types/block.go index e05f50b901..36ae42ce19 100644 --- a/plugin/consensus/qbft/types/block.go +++ b/plugin/consensus/qbft/types/block.go @@ -52,7 +52,7 @@ func (blockID BlockID) String() string { return Fmt("%X", blockID.Hash) } -//QbftBlock struct +// QbftBlock struct type QbftBlock struct { *tmtypes.QbftBlock } diff --git a/plugin/consensus/qbft/types/const.go b/plugin/consensus/qbft/types/const.go index 38c575a898..9eb3865517 100644 --- a/plugin/consensus/qbft/types/const.go +++ b/plugin/consensus/qbft/types/const.go @@ -12,7 +12,7 @@ import ( "github.com/33cn/chain33/types" ) -//authbls register +// authbls register const ( AuthBLS = 259 ) diff --git a/plugin/consensus/qbft/types/validator_set.go b/plugin/consensus/qbft/types/validator_set.go index c1c8e46069..65b582b0f3 100644 --- a/plugin/consensus/qbft/types/validator_set.go +++ b/plugin/consensus/qbft/types/validator_set.go @@ -431,8 +431,8 @@ func (valSet *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height // * over 2/3 of the power in old signed this block // // newSet is the validator set that signed this block -// * only votes from old are sufficient for 2/3 majority -// in the new set as well +// - only votes from old are sufficient for 2/3 majority +// in the new set as well // // That means that: // * 10% of the valset can't just declare themselves kings diff --git a/plugin/consensus/qbft/types/vote_set.go b/plugin/consensus/qbft/types/vote_set.go index a5144b8a08..af81d4e5ea 100644 --- a/plugin/consensus/qbft/types/vote_set.go +++ b/plugin/consensus/qbft/types/vote_set.go @@ -130,8 +130,10 @@ func (voteSet *VoteSet) Size() int { // AddVote Returns added=true if vote is valid and new. // Otherwise returns err=ErrVote[ -// UnexpectedStep | InvalidIndex | InvalidAddress | -// InvalidSignature | InvalidBlockHash | ConflictingVotes ] +// +// 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. @@ -698,10 +700,10 @@ func (voteSet *VoteSet) AddCommitVote(votes []*tmtypes.QbftVote, aggVote *tmtype //-------------------------------------------------------------------------------- /* - 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) +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 diff --git a/plugin/consensus/raft/block.go b/plugin/consensus/raft/block.go index 8e5aeffee2..766c0d0dd2 100644 --- a/plugin/consensus/raft/block.go +++ b/plugin/consensus/raft/block.go @@ -234,7 +234,7 @@ func (client *Client) readCommits(commitC <-chan *types.Block, errorC <-chan err } } -//轮询任务,去检测本机器是否为validator节点,如果是,则执行打包任务 +// 轮询任务,去检测本机器是否为validator节点,如果是,则执行打包任务 func (client *Client) pollingTask() { for { select { @@ -259,7 +259,7 @@ func (client *Client) pollingTask() { } } -//CmpBestBlock 比较newBlock是不是最优区块 +// CmpBestBlock 比较newBlock是不是最优区块 func (client *Client) CmpBestBlock(newBlock *types.Block, cmpBlock *types.Block) bool { return false } diff --git a/plugin/consensus/raft/raft.go b/plugin/consensus/raft/raft.go index 1270e3e878..48b9e103ba 100644 --- a/plugin/consensus/raft/raft.go +++ b/plugin/consensus/raft/raft.go @@ -68,7 +68,7 @@ type raftNode struct { restartC chan struct{} } -//Node ... +// Node ... type Node struct { *raftNode } @@ -105,7 +105,7 @@ func NewRaftNode(ctx context.Context, id int, join bool, peers []string, readOnl return commitC, errorC, rc.snapshotterReady, rc.validatorC } -// 启动raft节点 +// 启动raft节点 func (rc *raftNode) startRaft() { // 有snapshot就打开,没有则创建 if !fileutil.Exist(rc.snapdir) { diff --git a/plugin/consensus/tendermint/consensus_state.go b/plugin/consensus/tendermint/consensus_state.go index 1dd1a6e413..f84fcd6b7c 100644 --- a/plugin/consensus/tendermint/consensus_state.go +++ b/plugin/consensus/tendermint/consensus_state.go @@ -554,7 +554,7 @@ func (cs *ConsensusState) handleTxsAvailable(height int64) { switch cs.Step { case ttypes.RoundStepNewHeight: // timeoutCommit phase // +1ms to ensure RoundStepNewRound timeout always happens after RoundStepNewHeight - timeoutCommit := cs.StartTime.Sub(time.Now()) + 1*time.Millisecond + timeoutCommit := time.Until(cs.StartTime) + 1*time.Millisecond cs.scheduleTimeout(timeoutCommit, height, 0, ttypes.RoundStepNewRound) case ttypes.RoundStepNewRound: // after timeoutCommit cs.enterPropose(height, 0) @@ -566,7 +566,9 @@ func (cs *ConsensusState) handleTxsAvailable(height int64) { // Used internally by handleTimeout and handleMsg to make state transitions // Enter: `timeoutNewHeight` by startTime (commitTime+timeoutCommit), -// or, if SkipTimeout==true, after receiving all precommits from (height,round-1) +// +// or, if SkipTimeout==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) @@ -1195,11 +1197,11 @@ func (cs *ConsensusState) finalizeCommit(height int64) { block := cs.ProposalBlock if !ok { - panic(fmt.Sprintf("Cannot finalizeCommit, commit does not have two thirds majority")) + panic("Cannot finalizeCommit, commit does not have two thirds majority") } if !block.HashesTo(blockID.Hash) { - panic(fmt.Sprintf("Cannot finalizeCommit, ProposalBlock does not hash to commit hash")) + panic("Cannot finalizeCommit, ProposalBlock does not hash to commit hash") } if err := cs.blockExec.ValidateBlock(cs.state, block); err != nil { panic(fmt.Sprintf("+2/3 committed an invalid block: %v", err)) diff --git a/plugin/consensus/tendermint/node.go b/plugin/consensus/tendermint/node.go index 954cb8946d..2aad2d4f97 100644 --- a/plugin/consensus/tendermint/node.go +++ b/plugin/consensus/tendermint/node.go @@ -596,7 +596,7 @@ func (node *Node) reconnectToPeer(addr string) { tendermintlog.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start)) } -//--------------------------------------------------------------------- +// --------------------------------------------------------------------- func randomSleep(interval time.Duration) { r := time.Duration(ttypes.RandInt63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond time.Sleep(r + interval) diff --git a/plugin/consensus/tendermint/peer_set.go b/plugin/consensus/tendermint/peer_set.go index 180a5d5b6a..c5607f36de 100644 --- a/plugin/consensus/tendermint/peer_set.go +++ b/plugin/consensus/tendermint/peer_set.go @@ -165,7 +165,6 @@ func (ps *PeerSet) hasIP(peerIP net.IP) bool { return false } -// func (ps *PeerSet) GetIP(peerKey ID) net.IP { ps.mtx.Lock() ps.mtx.Unlock() @@ -225,7 +224,7 @@ func (ps *PeerSet) Remove(peer Peer) { delete(ps.lookup, peer.ID()) } -//-------------------------peer connection-------------------------------- +// -------------------------peer connection-------------------------------- func (pc *peerConn) ID() ID { if len(pc.id) != 0 { return pc.id diff --git a/plugin/consensus/tendermint/store.go b/plugin/consensus/tendermint/store.go index 032a6c2a57..3df7907dec 100644 --- a/plugin/consensus/tendermint/store.go +++ b/plugin/consensus/tendermint/store.go @@ -17,7 +17,7 @@ var ( stateKey = []byte("stateKey") ) -//ConsensusStore ... +// ConsensusStore ... type ConsensusStore struct { db dbm.DB } diff --git a/plugin/consensus/tendermint/tendermint.go b/plugin/consensus/tendermint/tendermint.go index 81c23c6226..8c3280208e 100644 --- a/plugin/consensus/tendermint/tendermint.go +++ b/plugin/consensus/tendermint/tendermint.go @@ -663,7 +663,7 @@ func (client *Client) Query_NodeInfo(req *types.ReqNil) (types.Message, error) { if val == nil { nodes = append(nodes, &tmtypes.ValNodeInfo{}) } else { - ipstr, idstr := "UNKOWN", "UNKOWN" + ipstr, idstr := "UNKNOWN", "UNKNOWN" pub, err := ttypes.ConsensusCrypto.PubKeyFromBytes(val.PubKey) if err != nil { tendermintlog.Error("Query_NodeInfo invalid pubkey", "err", err) diff --git a/plugin/consensus/tendermint/tools/nonePerf.go b/plugin/consensus/tendermint/tools/nonePerf.go index 1fdf2d2cff..b64bd3270f 100644 --- a/plugin/consensus/tendermint/tools/nonePerf.go +++ b/plugin/consensus/tendermint/tools/nonePerf.go @@ -510,7 +510,7 @@ func Get(ip string, hash string) { func setTxHeight(ip string) { url := "http://" + ip + ":8801" - poststr := fmt.Sprintf(`{"jsonrpc":"2.0","id":2,"method":"Chain33.GetLastHeader","params":[]}`) + poststr := `{"jsonrpc":"2.0","id":2,"method":"Chain33.GetLastHeader","params":[]}` resp, err := http.Post(url, "application/json", bytes.NewBufferString(poststr)) if err != nil { fmt.Println(err) diff --git a/plugin/consensus/tendermint/types/block.go b/plugin/consensus/tendermint/types/block.go index aecdf092a7..f50028d5b6 100644 --- a/plugin/consensus/tendermint/types/block.go +++ b/plugin/consensus/tendermint/types/block.go @@ -43,7 +43,7 @@ func (blockID BlockID) String() string { return Fmt(`%v`, blockID.Hash) } -//TendermintBlock struct +// TendermintBlock struct type TendermintBlock struct { *tmtypes.TendermintBlock } diff --git a/plugin/consensus/tendermint/types/const.go b/plugin/consensus/tendermint/types/const.go index 4c912cf50d..7d1e33e1b5 100644 --- a/plugin/consensus/tendermint/types/const.go +++ b/plugin/consensus/tendermint/types/const.go @@ -12,7 +12,7 @@ import ( "github.com/33cn/chain33/types" ) -//authbls register +// authbls register const ( AuthBLS = 259 ) diff --git a/plugin/consensus/tendermint/types/validator_set.go b/plugin/consensus/tendermint/types/validator_set.go index 8878b69776..681cdc1a20 100644 --- a/plugin/consensus/tendermint/types/validator_set.go +++ b/plugin/consensus/tendermint/types/validator_set.go @@ -394,8 +394,8 @@ func (valSet *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height // * over 2/3 of the power in old signed this block // // newSet is the validator set that signed this block -// * only votes from old are sufficient for 2/3 majority -// in the new set as well +// - only votes from old are sufficient for 2/3 majority +// in the new set as well // // That means that: // * 10% of the valset can't just declare themselves kings diff --git a/plugin/consensus/tendermint/types/vote_set.go b/plugin/consensus/tendermint/types/vote_set.go index f26ac62e54..0a21f87799 100644 --- a/plugin/consensus/tendermint/types/vote_set.go +++ b/plugin/consensus/tendermint/types/vote_set.go @@ -128,8 +128,10 @@ func (voteSet *VoteSet) Size() int { // AddVote Returns added=true if vote is valid and new. // Otherwise returns err=ErrVote[ -// UnexpectedStep | InvalidIndex | InvalidAddress | -// InvalidSignature | InvalidBlockHash | ConflictingVotes ] +// +// 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. @@ -650,10 +652,10 @@ func (voteSet *VoteSet) MakeCommit() *tmtypes.TendermintCommit { //-------------------------------------------------------------------------------- /* - 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) +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 diff --git a/plugin/consensus/ticket/ticket.go b/plugin/consensus/ticket/ticket.go index 6f73f72844..270d7e0742 100644 --- a/plugin/consensus/ticket/ticket.go +++ b/plugin/consensus/ticket/ticket.go @@ -607,9 +607,7 @@ func (client *Client) delTicket(ticketID string) { if client.ticketsMap == nil || len(ticketID) == 0 { return } - if _, ok := client.ticketsMap[ticketID]; ok { - delete(client.ticketsMap, ticketID) - } + delete(client.ticketsMap, ticketID) } // Miner ticket miner function diff --git a/plugin/consensus/ticket/ticket_test.go b/plugin/consensus/ticket/ticket_test.go index 62b7220373..8151751d12 100755 --- a/plugin/consensus/ticket/ticket_test.go +++ b/plugin/consensus/ticket/ticket_test.go @@ -6,10 +6,11 @@ package ticket import ( "fmt" - "github.com/btcsuite/btcd/btcec/v2" "testing" "time" + "github.com/btcsuite/btcd/btcec/v2" + "github.com/33cn/chain33/account" "github.com/33cn/chain33/common/crypto" vrf "github.com/33cn/chain33/common/vrf/secp256k1" diff --git a/plugin/crypto/bls/bls.go b/plugin/crypto/bls/bls.go index 09c18280dd..6aa81b5903 100644 --- a/plugin/crypto/bls/bls.go +++ b/plugin/crypto/bls/bls.go @@ -16,7 +16,7 @@ import ( "github.com/phoreproject/bls/g1pubs" ) -//setting +// setting const ( BLSPrivateKeyLength = 32 BLSPublicKeyLength = 48 @@ -90,7 +90,7 @@ func (d Driver) Validate(msg, pub, sig []byte) error { return crypto.BasicValidation(d, msg, pub, sig) } -//Aggregate aggregates signatures together into a new signature. +// Aggregate aggregates signatures together into a new signature. func (d Driver) Aggregate(sigs []crypto.Signature) (crypto.Signature, error) { if len(sigs) == 0 { return nil, errors.New("no signatures to aggregate") @@ -107,7 +107,7 @@ func (d Driver) Aggregate(sigs []crypto.Signature) (crypto.Signature, error) { return SignatureBLS(agsig.Serialize()), nil } -//AggregatePublic aggregates public keys together into a new PublicKey. +// AggregatePublic aggregates public keys together into a new PublicKey. func (d Driver) AggregatePublic(pubs []crypto.PubKey) (crypto.PubKey, error) { if len(pubs) == 0 { return nil, errors.New("no public keys to aggregate") @@ -234,7 +234,7 @@ func (privKey PrivKeyBLS) Equals(other crypto.PrivKey) bool { // String convert to string func (privKey PrivKeyBLS) String() string { - return fmt.Sprintf("PrivKeyBLS{*****}") + return "PrivKeyBLS{*****}" } // PubKeyBLS PubKey diff --git a/plugin/crypto/bls/bls_test.go b/plugin/crypto/bls/bls_test.go index 4cc15851fa..d9fe9c2df8 100644 --- a/plugin/crypto/bls/bls_test.go +++ b/plugin/crypto/bls/bls_test.go @@ -117,7 +117,7 @@ func TestAggregate(t *testing.T) { assert.Error(t, err) } -//benchmark +// benchmark func BenchmarkBLSAggregateSignature(b *testing.B) { msg := []byte(">16 character identical message") n := 200 diff --git a/plugin/dapp/accountmanager/executor/account_test.go b/plugin/dapp/accountmanager/executor/account_test.go index 68436d2ffa..23ab20289d 100644 --- a/plugin/dapp/accountmanager/executor/account_test.go +++ b/plugin/dapp/accountmanager/executor/account_test.go @@ -307,7 +307,7 @@ func CreateApply(apply *et.Apply, privKey string) (tx *types.Transaction, err er return tx, nil } -//模拟区块中交易得执行过程 +// 模拟区块中交易得执行过程 func Exec_Block(t *testing.T, stateDB db.DB, kvdb db.KVDB, env *execEnv, txs ...*types.Transaction) error { cfg := types.NewChain33Config(types.GetDefaultCfgstring()) cfg.SetTitleOnlyForTest("chain33") diff --git a/plugin/dapp/accountmanager/executor/accountdb.go b/plugin/dapp/accountmanager/executor/accountdb.go index 9e45c4ae05..0bfc1fa729 100644 --- a/plugin/dapp/accountmanager/executor/accountdb.go +++ b/plugin/dapp/accountmanager/executor/accountdb.go @@ -42,7 +42,7 @@ type Action struct { api client.QueueProtocolAPI } -//NewAction ... +// NewAction ... func NewAction(e *Accountmanager, tx *types.Transaction, index int) *Action { hash := tx.Hash() fromaddr := tx.From() @@ -50,18 +50,18 @@ func NewAction(e *Accountmanager, tx *types.Transaction, index int) *Action { e.GetBlockTime(), e.GetHeight(), dapp.ExecAddress(string(tx.Execer)), e.GetLocalDB(), index, e.GetAPI()} } -//GetIndex get index 主键索引,实际上是以过期时间为主键 +// GetIndex get index 主键索引,实际上是以过期时间为主键 func (a *Action) GetIndex() int64 { return a.blocktime*types.MaxTxsPerBlock + int64(a.index) } -//GetKVSet get kv set +// GetKVSet get kv set func (a *Action) GetKVSet(account *et.Account) (kvset []*types.KeyValue) { kvset = append(kvset, &types.KeyValue{Key: calcAccountKey(account.AccountID), Value: types.Encode(account)}) return kvset } -//Register ... +// Register ... func (a *Action) Register(payload *et.Register) (*types.Receipt, error) { var logs []*types.ReceiptLog account1, err := findAccountByID(a.localDB, payload.AccountID) @@ -92,7 +92,7 @@ func (a *Action) Register(payload *et.Register) (*types.Receipt, error) { return receipts, nil } -//Reset 为了避免别人恶意重置别人的帐号,这个操作仅有系统管理员有权限去操作 +// Reset 为了避免别人恶意重置别人的帐号,这个操作仅有系统管理员有权限去操作 func (a *Action) Reset(payload *et.ResetKey) (*types.Receipt, error) { var logs []*types.ReceiptLog cfg := a.api.GetConfig() @@ -119,7 +119,7 @@ func (a *Action) Reset(payload *et.ResetKey) (*types.Receipt, error) { return receipts, nil } -//Transfer ... +// Transfer ... func (a *Action) Transfer(payload *et.Transfer) (*types.Receipt, error) { var logs []*types.ReceiptLog var kvs []*types.KeyValue @@ -197,7 +197,7 @@ func (a *Action) Transfer(payload *et.Transfer) (*types.Receipt, error) { return receipts, nil } -//Supervise ... +// Supervise ... func (a *Action) Supervise(payload *et.Supervise) (*types.Receipt, error) { //鉴权,看一下地址是否时管理员地址 cfg := a.api.GetConfig() @@ -240,7 +240,7 @@ func (a *Action) Supervise(payload *et.Supervise) (*types.Receipt, error) { return receipts, nil } -//Apply ... +// Apply ... func (a *Action) Apply(payload *et.Apply) (*types.Receipt, error) { var logs []*types.ReceiptLog var kvs []*types.KeyValue @@ -363,7 +363,7 @@ func getConfigKey(key string, db dbm.KV) ([]byte, error) { return value, nil } -//正序遍历数据,与传入时间进行对比,看是否逾期 +// 正序遍历数据,与传入时间进行对比,看是否逾期 func findAccountListByIndex(localdb dbm.KV, expireTime int64, primaryKey string) (*et.ReplyAccountList, error) { table := NewAccountTable(localdb) var rows []*tab.Row diff --git a/plugin/dapp/accountmanager/executor/accountmanager.go b/plugin/dapp/accountmanager/executor/accountmanager.go index 429f940fe7..5d9b1fcba4 100644 --- a/plugin/dapp/accountmanager/executor/accountmanager.go +++ b/plugin/dapp/accountmanager/executor/accountmanager.go @@ -31,7 +31,7 @@ func InitExecType() { ety.InitFuncList(types.ListMethod(&Accountmanager{})) } -//Accountmanager ... +// Accountmanager ... type Accountmanager struct { drivers.DriverBase } @@ -48,12 +48,12 @@ func GetName() string { return newAccountmanager().GetName() } -//GetDriverName ... +// GetDriverName ... func (a *Accountmanager) GetDriverName() string { return driverName } -//ExecutorOrder Exec 的时候 同时执行 ExecLocal +// ExecutorOrder Exec 的时候 同时执行 ExecLocal func (a *Accountmanager) ExecutorOrder() int64 { return drivers.ExecLocalSameTime } @@ -84,7 +84,7 @@ func (a *Accountmanager) CheckTx(tx *types.Transaction, index int) error { return nil } -//CheckAccountIDIsExist ... +// CheckAccountIDIsExist ... func (a *Accountmanager) CheckAccountIDIsExist(accountID string) bool { _, err := findAccountByID(a.GetLocalDB(), accountID) return err != types.ErrNotFound diff --git a/plugin/dapp/accountmanager/executor/exec_local.go b/plugin/dapp/accountmanager/executor/exec_local.go index e5fb12706c..8e1c4e5baa 100644 --- a/plugin/dapp/accountmanager/executor/exec_local.go +++ b/plugin/dapp/accountmanager/executor/exec_local.go @@ -10,7 +10,7 @@ import ( * 非关键数据,本地存储(localDB), 用于辅助查询,效率高 */ -//ExecLocal_Register ... +// ExecLocal_Register ... func (a *Accountmanager) ExecLocal_Register(payload *et.Register, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { dbSet := &types.LocalDBSet{} if receiptData.Ty == types.ExecOk { @@ -38,7 +38,7 @@ func (a *Accountmanager) ExecLocal_Register(payload *et.Register, tx *types.Tran return a.addAutoRollBack(tx, dbSet.KV), nil } -//ExecLocal_ResetKey ... +// ExecLocal_ResetKey ... func (a *Accountmanager) ExecLocal_ResetKey(payload *et.ResetKey, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { dbSet := &types.LocalDBSet{} if receiptData.Ty == types.ExecOk { @@ -65,7 +65,7 @@ func (a *Accountmanager) ExecLocal_ResetKey(payload *et.ResetKey, tx *types.Tran return a.addAutoRollBack(tx, dbSet.KV), nil } -//ExecLocal_Apply ... +// ExecLocal_Apply ... func (a *Accountmanager) ExecLocal_Apply(payload *et.Apply, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { dbSet := &types.LocalDBSet{} if receiptData.Ty == types.ExecOk { @@ -92,7 +92,7 @@ func (a *Accountmanager) ExecLocal_Apply(payload *et.Apply, tx *types.Transactio return a.addAutoRollBack(tx, dbSet.KV), nil } -//ExecLocal_Transfer ... +// ExecLocal_Transfer ... func (a *Accountmanager) ExecLocal_Transfer(payload *et.Transfer, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { dbSet := &types.LocalDBSet{} if receiptData.Ty == types.ExecOk { @@ -119,7 +119,7 @@ func (a *Accountmanager) ExecLocal_Transfer(payload *et.Transfer, tx *types.Tran return a.addAutoRollBack(tx, dbSet.KV), nil } -//ExecLocal_Supervise ... +// ExecLocal_Supervise ... func (a *Accountmanager) ExecLocal_Supervise(payload *et.Supervise, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { dbSet := &types.LocalDBSet{} if receiptData.Ty == types.ExecOk { @@ -170,7 +170,7 @@ func (a *Accountmanager) ExecLocal_Supervise(payload *et.Supervise, tx *types.Tr return a.addAutoRollBack(tx, dbSet.KV), nil } -//设置自动回滚 +// 设置自动回滚 func (a *Accountmanager) addAutoRollBack(tx *types.Transaction, kv []*types.KeyValue) *types.LocalDBSet { dbSet := &types.LocalDBSet{} dbSet.KV = a.AddRollbackKV(tx, tx.Execer, kv) diff --git a/plugin/dapp/accountmanager/executor/query.go b/plugin/dapp/accountmanager/executor/query.go index 06c07eec3b..20c937e2aa 100644 --- a/plugin/dapp/accountmanager/executor/query.go +++ b/plugin/dapp/accountmanager/executor/query.go @@ -5,27 +5,27 @@ import ( et "github.com/33cn/plugin/plugin/dapp/accountmanager/types" ) -//Query_QueryAccountByID 根据ID查询账户信息 +// Query_QueryAccountByID 根据ID查询账户信息 func (a *Accountmanager) Query_QueryAccountByID(in *et.QueryAccountByID) (types.Message, error) { return findAccountByID(a.GetLocalDB(), in.AccountID) } -//Query_QueryAccountByAddr 根据ID查询账户信息 +// Query_QueryAccountByAddr 根据ID查询账户信息 func (a *Accountmanager) Query_QueryAccountByAddr(in *et.QueryAccountByAddr) (types.Message, error) { return findAccountByAddr(a.GetLocalDB(), in.Addr) } -//Query_QueryAccountsByStatus 根据状态查询账户列表|| 账户状态 1 正常, 2表示冻结, 3表示锁定 4,过期注销 +// Query_QueryAccountsByStatus 根据状态查询账户列表|| 账户状态 1 正常, 2表示冻结, 3表示锁定 4,过期注销 func (a *Accountmanager) Query_QueryAccountsByStatus(in *et.QueryAccountsByStatus) (types.Message, error) { return findAccountListByStatus(a.GetLocalDB(), in.Status, in.Direction, in.PrimaryKey) } -//Query_QueryExpiredAccounts 查询逾期注销的账户列表 +// Query_QueryExpiredAccounts 查询逾期注销的账户列表 func (a *Accountmanager) Query_QueryExpiredAccounts(in *et.QueryExpiredAccounts) (types.Message, error) { return findAccountListByIndex(a.GetLocalDB(), in.ExpiredTime, in.PrimaryKey) } -//Query_QueryBalanceByID 根据ID查询账户余额 +// Query_QueryBalanceByID 根据ID查询账户余额 func (a *Accountmanager) Query_QueryBalanceByID(in *et.QueryBalanceByID) (types.Message, error) { return queryBalanceByID(a.GetStateDB(), a.GetLocalDB(), a.GetAPI().GetConfig(), a.GetName(), in) } diff --git a/plugin/dapp/accountmanager/executor/tables.go b/plugin/dapp/accountmanager/executor/tables.go index 7e3fe32664..651660e28a 100644 --- a/plugin/dapp/accountmanager/executor/tables.go +++ b/plugin/dapp/accountmanager/executor/tables.go @@ -29,13 +29,13 @@ var opt_account = &table.Option{ Index: []string{"status", "accountID", "addr"}, } -//状态数据库中存储具体账户信息 +// 状态数据库中存储具体账户信息 func calcAccountKey(accountID string) []byte { key := fmt.Sprintf("%s"+"accountID:%s", KeyPrefixStateDB, accountID) return []byte(key) } -//NewAccountTable ... +// NewAccountTable ... func NewAccountTable(kvdb db.KV) *table.Table { rowmeta := NewAccountRow() table, err := table.NewTable(rowmeta, kvdb, opt_account) @@ -45,22 +45,22 @@ func NewAccountTable(kvdb db.KV) *table.Table { return table } -//AccountRow account table meta 结构 +// AccountRow account table meta 结构 type AccountRow struct { *aty.Account } -//NewAccountRow 新建一个meta 结构 +// NewAccountRow 新建一个meta 结构 func NewAccountRow() *AccountRow { return &AccountRow{Account: &aty.Account{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存eventid) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存eventid) func (m *AccountRow) CreateRow() *table.Row { return &table.Row{Data: &aty.Account{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (m *AccountRow) SetPayload(data types.Message) error { if txdata, ok := data.(*aty.Account); ok { m.Account = txdata @@ -69,7 +69,7 @@ func (m *AccountRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (m *AccountRow) Get(key string) ([]byte, error) { if key == "accountID" { return []byte(m.AccountID), nil diff --git a/plugin/dapp/accountmanager/types/accountmanager.go b/plugin/dapp/accountmanager/types/accountmanager.go index e500f49771..6b3f521bea 100644 --- a/plugin/dapp/accountmanager/types/accountmanager.go +++ b/plugin/dapp/accountmanager/types/accountmanager.go @@ -44,7 +44,7 @@ const ( TyApplyLog ) -//状态 +// 状态 const ( Normal = int32(iota) Frozen @@ -52,7 +52,7 @@ const ( Expired ) -//supervior op +// supervior op const ( UnknownSupervisorOp = int32(iota) Freeze @@ -61,14 +61,14 @@ const ( Authorize ) -//apply op +// apply op const ( UnknownApplyOp = int32(iota) RevokeReset EnforceReset ) -//list ... +// list ... const ( ListDESC = int32(0) ListASC = int32(1) @@ -119,12 +119,12 @@ func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(AccountmanagerX, NewType(cfg)) } -//AccountmanagerType ... +// AccountmanagerType ... type AccountmanagerType struct { types.ExecTypeBase } -//NewType ... +// NewType ... func NewType(cfg *types.Chain33Config) *AccountmanagerType { c := &AccountmanagerType{} c.SetChild(c) diff --git a/plugin/dapp/accountmanager/types/accountmanager.pb.go b/plugin/dapp/accountmanager/types/accountmanager.pb.go index 21de4c831b..a78860e9b7 100644 --- a/plugin/dapp/accountmanager/types/accountmanager.pb.go +++ b/plugin/dapp/accountmanager/types/accountmanager.pb.go @@ -188,7 +188,7 @@ func (*AccountmanagerAction) XXX_OneofWrappers() []interface{} { } } -//注册 +// 注册 type Register struct { AccountID string `protobuf:"bytes,1,opt,name=accountID,proto3" json:"accountID,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` @@ -228,7 +228,7 @@ func (m *Register) GetAccountID() string { return "" } -//重置公钥 +// 重置公钥 type ResetKey struct { AccountID string `protobuf:"bytes,1,opt,name=accountID,proto3" json:"accountID,omitempty"` Addr string `protobuf:"bytes,2,opt,name=addr,proto3" json:"addr,omitempty"` @@ -276,7 +276,7 @@ func (m *ResetKey) GetAddr() string { return "" } -//用户申请服务 +// 用户申请服务 type Apply struct { AccountID string `protobuf:"bytes,1,opt,name=accountID,proto3" json:"accountID,omitempty"` //操作, 1 撤销账户公钥重置, 2 锁定期结束后,执行重置公钥操作 @@ -325,7 +325,7 @@ func (m *Apply) GetOp() int32 { return 0 } -//合约内部账户之间转账 +// 合约内部账户之间转账 type Transfer struct { //资产类型 及转账金额 Asset *types.Asset `protobuf:"bytes,1,opt,name=asset,proto3" json:"asset,omitempty"` @@ -384,7 +384,7 @@ func (m *Transfer) GetToAccountID() string { return "" } -//管理员监管操作 +// 管理员监管操作 type Supervise struct { //账户名单 AccountIDs []string `protobuf:"bytes,1,rep,name=accountIDs,proto3" json:"accountIDs,omitempty"` @@ -696,7 +696,7 @@ func (m *TransferReceipt) GetIndex() int64 { return 0 } -//回执日志 +// 回执日志 type SuperviseReceipt struct { Accounts []*Account `protobuf:"bytes,1,rep,name=accounts,proto3" json:"accounts,omitempty"` Op int32 `protobuf:"varint,2,opt,name=op,proto3" json:"op,omitempty"` diff --git a/plugin/dapp/autonomy/executor/autonomy.go b/plugin/dapp/autonomy/executor/autonomy.go index 9301bfc23a..ae5b4be59f 100644 --- a/plugin/dapp/autonomy/executor/autonomy.go +++ b/plugin/dapp/autonomy/executor/autonomy.go @@ -38,7 +38,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Autonomy{})) diff --git a/plugin/dapp/autonomy/executor/boardaction.go b/plugin/dapp/autonomy/executor/boardaction.go index a9ee32dfa1..ddfd2f1edd 100644 --- a/plugin/dapp/autonomy/executor/boardaction.go +++ b/plugin/dapp/autonomy/executor/boardaction.go @@ -452,7 +452,7 @@ func (a *action) votePropBoard(voteProb *auty.VoteProposalBoard) (*types.Receipt return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//统计参与率的时候,计算弃权票,但是统计赞成率的时候,忽略弃权票。比如10票,4票赞成,3票反对,2票弃权,那么参与率是 90%, 赞成 4/7 反对 3/7 +// 统计参与率的时候,计算弃权票,但是统计赞成率的时候,忽略弃权票。比如10票,4票赞成,3票反对,2票弃权,那么参与率是 90%, 赞成 4/7 反对 3/7 func isApproved(totalVotes, approveVotes, opposeVotes, quitVotes, attendRation, approveRatio int32, autoCfg *AutonomyParam) bool { if attendRation <= 0 { attendRation = autoCfg.PubAttendRatio @@ -733,7 +733,7 @@ func (a *action) checkVotesRecord(addrs []string, key []byte) (*auty.VotesRecord return &votes, nil } -//新增addr场景,任一probAddr在当前board里即返回true +// 新增addr场景,任一probAddr在当前board里即返回true func checkAddrInBoard(act *auty.ActiveBoard, probAddrs map[string]struct{}) bool { for _, board := range act.Boards { if _, ok := probAddrs[board]; ok { @@ -765,7 +765,7 @@ func (a *action) addPropBoard(prob *auty.ProposalBoard, mpBd map[string]struct{} return act, nil } -//删除addr场景,若任一proposal addr不存在 则返回true, +// 删除addr场景,若任一proposal addr不存在 则返回true, func checkAddrNotInBoard(act *auty.ActiveBoard, prob *auty.ProposalBoard) error { actBoards := make(map[string]bool) for _, board := range act.Boards { @@ -781,7 +781,7 @@ func checkAddrNotInBoard(act *auty.ActiveBoard, prob *auty.ProposalBoard) error return nil } -//这里只考虑Board,不考虑revBoard +// 这里只考虑Board,不考虑revBoard func (a *action) delPropBoard(prob *auty.ProposalBoard, mpBd map[string]struct{}) (*auty.ActiveBoard, error) { act, err := a.getActiveBoard() if err != nil { diff --git a/plugin/dapp/autonomy/executor/boardtable.go b/plugin/dapp/autonomy/executor/boardtable.go index e83ccbf06d..dcbc960163 100644 --- a/plugin/dapp/autonomy/executor/boardtable.go +++ b/plugin/dapp/autonomy/executor/boardtable.go @@ -24,7 +24,7 @@ var boardOpt = &table.Option{ Index: []string{"addr", "status", "addr_status"}, } -//NewBoardTable 新建表 +// NewBoardTable 新建表 func NewBoardTable(kvdb db.KV) *table.Table { rowmeta := NewBoardRow() newTable, err := table.NewTable(rowmeta, kvdb, boardOpt) @@ -34,22 +34,22 @@ func NewBoardTable(kvdb db.KV) *table.Table { return newTable } -//BoardRow table meta 结构 +// BoardRow table meta 结构 type BoardRow struct { *auty.AutonomyProposalBoard } -//NewBoardRow 新建一个meta 结构 +// NewBoardRow 新建一个meta 结构 func NewBoardRow() *BoardRow { return &BoardRow{AutonomyProposalBoard: &auty.AutonomyProposalBoard{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) func (r *BoardRow) CreateRow() *table.Row { return &table.Row{Data: &auty.AutonomyProposalBoard{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *BoardRow) SetPayload(data types.Message) error { if d, ok := data.(*auty.AutonomyProposalBoard); ok { r.AutonomyProposalBoard = d @@ -58,7 +58,7 @@ func (r *BoardRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *BoardRow) Get(key string) ([]byte, error) { if key == "heightindex" { return []byte(dapp.HeightIndexStr(r.Height, int64(r.Index))), nil diff --git a/plugin/dapp/autonomy/executor/changeaction.go b/plugin/dapp/autonomy/executor/changeaction.go index 8de20fbc97..3676fbe7a0 100644 --- a/plugin/dapp/autonomy/executor/changeaction.go +++ b/plugin/dapp/autonomy/executor/changeaction.go @@ -206,9 +206,7 @@ func (a *action) votePropChange(voteProb *auty.VoteProposalChange) (*types.Recei if ch.Cancel { mpBd[ch.Addr] = struct{}{} } else { - if _, ok := mpBd[ch.Addr]; ok { - delete(mpBd, ch.Addr) - } + delete(mpBd, ch.Addr) } } } @@ -383,7 +381,7 @@ func (a *action) getProposalChange(ID string) (*auty.AutonomyProposalChange, err return cur, nil } -//新的方案只允许替换board里面的成员,而且是本用户申请,不允许从revBoard恢复 +// 新的方案只允许替换board里面的成员,而且是本用户申请,不允许从revBoard恢复 func (a *action) replaceBoard(act *auty.ActiveBoard, change []*auty.Change) (*auty.ActiveBoard, error) { //一个成员只允许替换一个新的 if len(change) > 1 { diff --git a/plugin/dapp/autonomy/executor/changetable.go b/plugin/dapp/autonomy/executor/changetable.go index 9dd15ac297..5566a16e71 100644 --- a/plugin/dapp/autonomy/executor/changetable.go +++ b/plugin/dapp/autonomy/executor/changetable.go @@ -24,7 +24,7 @@ var changeOpt = &table.Option{ Index: []string{"addr", "status", "addr_status"}, } -//NewChangeTable 新建表 +// NewChangeTable 新建表 func NewChangeTable(kvdb db.KV) *table.Table { rowmeta := NewChangeRow() newTable, err := table.NewTable(rowmeta, kvdb, changeOpt) @@ -34,22 +34,22 @@ func NewChangeTable(kvdb db.KV) *table.Table { return newTable } -//ChangeRow table meta 结构 +// ChangeRow table meta 结构 type ChangeRow struct { *auty.AutonomyProposalChange } -//NewChangeRow 新建一个meta 结构 +// NewChangeRow 新建一个meta 结构 func NewChangeRow() *ChangeRow { return &ChangeRow{AutonomyProposalChange: &auty.AutonomyProposalChange{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) func (r *ChangeRow) CreateRow() *table.Row { return &table.Row{Data: &auty.AutonomyProposalChange{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *ChangeRow) SetPayload(data types.Message) error { if d, ok := data.(*auty.AutonomyProposalChange); ok { r.AutonomyProposalChange = d @@ -58,7 +58,7 @@ func (r *ChangeRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *ChangeRow) Get(key string) ([]byte, error) { if key == "heightindex" { return []byte(dapp.HeightIndexStr(r.Height, int64(r.Index))), nil diff --git a/plugin/dapp/autonomy/executor/itemtable.go b/plugin/dapp/autonomy/executor/itemtable.go index ef24f202e2..308a123f0c 100644 --- a/plugin/dapp/autonomy/executor/itemtable.go +++ b/plugin/dapp/autonomy/executor/itemtable.go @@ -24,7 +24,7 @@ var itemOpt = &table.Option{ Index: []string{"addr", "status", "addr_status"}, } -//NewItemTable 新建表 +// NewItemTable 新建表 func NewItemTable(kvdb db.KV) *table.Table { rowmeta := NewItemRow() newTable, err := table.NewTable(rowmeta, kvdb, itemOpt) @@ -34,22 +34,22 @@ func NewItemTable(kvdb db.KV) *table.Table { return newTable } -//ItemRow table meta 结构 +// ItemRow table meta 结构 type ItemRow struct { *auty.AutonomyProposalItem } -//NewItemRow 新建一个meta 结构 +// NewItemRow 新建一个meta 结构 func NewItemRow() *ItemRow { return &ItemRow{AutonomyProposalItem: &auty.AutonomyProposalItem{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) func (r *ItemRow) CreateRow() *table.Row { return &table.Row{Data: &auty.AutonomyProposalItem{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *ItemRow) SetPayload(data types.Message) error { if d, ok := data.(*auty.AutonomyProposalItem); ok { r.AutonomyProposalItem = d @@ -58,7 +58,7 @@ func (r *ItemRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *ItemRow) Get(key string) ([]byte, error) { if key == "heightindex" { return []byte(dapp.HeightIndexStr(r.Height, int64(r.Index))), nil diff --git a/plugin/dapp/autonomy/executor/projecttable.go b/plugin/dapp/autonomy/executor/projecttable.go index b785e92574..8aea6883bc 100644 --- a/plugin/dapp/autonomy/executor/projecttable.go +++ b/plugin/dapp/autonomy/executor/projecttable.go @@ -24,7 +24,7 @@ var projectOpt = &table.Option{ Index: []string{"addr", "status", "addr_status"}, } -//NewProjectTable 新建表 +// NewProjectTable 新建表 func NewProjectTable(kvdb db.KV) *table.Table { rowmeta := NewProjectRow() newTable, err := table.NewTable(rowmeta, kvdb, projectOpt) @@ -34,22 +34,22 @@ func NewProjectTable(kvdb db.KV) *table.Table { return newTable } -//ProjectRow table meta 结构 +// ProjectRow table meta 结构 type ProjectRow struct { *auty.AutonomyProposalProject } -//NewProjectRow 新建一个meta 结构 +// NewProjectRow 新建一个meta 结构 func NewProjectRow() *ProjectRow { return &ProjectRow{AutonomyProposalProject: &auty.AutonomyProposalProject{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) func (r *ProjectRow) CreateRow() *table.Row { return &table.Row{Data: &auty.AutonomyProposalProject{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *ProjectRow) SetPayload(data types.Message) error { if d, ok := data.(*auty.AutonomyProposalProject); ok { r.AutonomyProposalProject = d @@ -58,7 +58,7 @@ func (r *ProjectRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *ProjectRow) Get(key string) ([]byte, error) { if key == "heightindex" { return []byte(dapp.HeightIndexStr(r.Height, int64(r.Index))), nil diff --git a/plugin/dapp/autonomy/executor/ruleaction_test.go b/plugin/dapp/autonomy/executor/ruleaction_test.go index d6eecd0194..1d07f659c4 100644 --- a/plugin/dapp/autonomy/executor/ruleaction_test.go +++ b/plugin/dapp/autonomy/executor/ruleaction_test.go @@ -43,7 +43,7 @@ func TestPropRule(t *testing.T) { PubOpposeRatio: int32(autoCfg.MaxPubOpposeRatio), ProposalAmount: autoCfg.MaxProposalAmount * types.DefaultCoinPrecision, LargeProjectAmount: autoCfg.MaxLargeProjectAmount * types.DefaultCoinPrecision, - PublicPeriod: int32(autoCfg.MaxPublicPeriod), + PublicPeriod: autoCfg.MaxPublicPeriod, PubAttendRatio: int32(autoCfg.MaxPubAttendRatio), PubApproveRatio: int32(autoCfg.MaxPubApproveRatio), }, @@ -56,7 +56,7 @@ func TestPropRule(t *testing.T) { PubOpposeRatio: int32(autoCfg.MinPubOpposeRatio), ProposalAmount: autoCfg.MinProposalAmount * types.DefaultCoinPrecision, LargeProjectAmount: autoCfg.MinLargeProjectAmount * types.DefaultCoinPrecision, - PublicPeriod: int32(autoCfg.MinPublicPeriod), + PublicPeriod: autoCfg.MinPublicPeriod, PubAttendRatio: int32(autoCfg.MinPubAttendRatio), PubApproveRatio: int32(autoCfg.MinPubApproveRatio), }, @@ -69,7 +69,7 @@ func TestPropRule(t *testing.T) { PubOpposeRatio: int32(autoCfg.MinPubOpposeRatio) - 1, ProposalAmount: autoCfg.MinProposalAmount*types.DefaultCoinPrecision - 1, LargeProjectAmount: autoCfg.MinLargeProjectAmount*types.DefaultCoinPrecision - 1, - PublicPeriod: int32(autoCfg.MinPublicPeriod) - 1, + PublicPeriod: autoCfg.MinPublicPeriod - 1, PubAttendRatio: int32(autoCfg.MinPubAttendRatio) - 1, PubApproveRatio: int32(autoCfg.MinPubApproveRatio) - 1, }, @@ -82,7 +82,7 @@ func TestPropRule(t *testing.T) { PubOpposeRatio: int32(autoCfg.MaxPubOpposeRatio) + 1, ProposalAmount: autoCfg.MaxProposalAmount*types.DefaultCoinPrecision + 1, LargeProjectAmount: autoCfg.MaxLargeProjectAmount*types.DefaultCoinPrecision + 1, - PublicPeriod: int32(autoCfg.MaxPublicPeriod) + 1, + PublicPeriod: autoCfg.MaxPublicPeriod + 1, PubAttendRatio: int32(autoCfg.MaxPubAttendRatio) + 1, PubApproveRatio: int32(autoCfg.MaxPubApproveRatio) + 1, }, @@ -95,7 +95,7 @@ func TestPropRule(t *testing.T) { PubOpposeRatio: int32(autoCfg.MinPubOpposeRatio) + 1, ProposalAmount: autoCfg.MinProposalAmount*types.DefaultCoinPrecision + 1, LargeProjectAmount: autoCfg.MinLargeProjectAmount*types.DefaultCoinPrecision + 1, - PublicPeriod: int32(autoCfg.MinPublicPeriod) + 1, + PublicPeriod: autoCfg.MinPublicPeriod + 1, PubAttendRatio: int32(autoCfg.MinPubAttendRatio) + 1, PubApproveRatio: int32(autoCfg.MinPubApproveRatio) + 1, }, diff --git a/plugin/dapp/autonomy/executor/ruletable.go b/plugin/dapp/autonomy/executor/ruletable.go index a855d9049e..48fdae9940 100644 --- a/plugin/dapp/autonomy/executor/ruletable.go +++ b/plugin/dapp/autonomy/executor/ruletable.go @@ -24,7 +24,7 @@ var ruleOpt = &table.Option{ Index: []string{"addr", "status", "addr_status"}, } -//NewRuleTable 新建表 +// NewRuleTable 新建表 func NewRuleTable(kvdb db.KV) *table.Table { rowmeta := NewRuleRow() newTable, err := table.NewTable(rowmeta, kvdb, ruleOpt) @@ -34,22 +34,22 @@ func NewRuleTable(kvdb db.KV) *table.Table { return newTable } -//RuleRow table meta 结构 +// RuleRow table meta 结构 type RuleRow struct { *auty.AutonomyProposalRule } -//NewRuleRow 新建一个meta 结构 +// NewRuleRow 新建一个meta 结构 func NewRuleRow() *RuleRow { return &RuleRow{AutonomyProposalRule: &auty.AutonomyProposalRule{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) func (r *RuleRow) CreateRow() *table.Row { return &table.Row{Data: &auty.AutonomyProposalRule{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *RuleRow) SetPayload(data types.Message) error { if d, ok := data.(*auty.AutonomyProposalRule); ok { r.AutonomyProposalRule = d @@ -58,7 +58,7 @@ func (r *RuleRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *RuleRow) Get(key string) ([]byte, error) { if key == "heightindex" { return []byte(dapp.HeightIndexStr(r.Height, int64(r.Index))), nil diff --git a/plugin/dapp/autonomy/types/const.go b/plugin/dapp/autonomy/types/const.go index 79d4bc88ea..6521646654 100644 --- a/plugin/dapp/autonomy/types/const.go +++ b/plugin/dapp/autonomy/types/const.go @@ -136,9 +136,9 @@ const ( ListProposalItem = "ListProposalItem" ) -//包的名字可以通过配置文件来配置 -//建议用github的组织名称,或者用户名字开头, 再加上自己的插件的名字 -//如果发生重名,可以通过配置文件修改这些名字 +// 包的名字可以通过配置文件来配置 +// 建议用github的组织名称,或者用户名字开头, 再加上自己的插件的名字 +// 如果发生重名,可以通过配置文件修改这些名字 var ( AutonomyX = "autonomy" ExecerAutonomy = []byte(AutonomyX) diff --git a/plugin/dapp/autonomy/types/lcommon.pb.go b/plugin/dapp/autonomy/types/lcommon.pb.go index 443d8aa7c3..c40753d1bc 100644 --- a/plugin/dapp/autonomy/types/lcommon.pb.go +++ b/plugin/dapp/autonomy/types/lcommon.pb.go @@ -25,7 +25,7 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -//三种投票选项 +// 三种投票选项 type AutonomyVoteOption int32 const ( diff --git a/plugin/dapp/autonomy/types/types.go b/plugin/dapp/autonomy/types/types.go index 3c55da1460..84b7b0f524 100644 --- a/plugin/dapp/autonomy/types/types.go +++ b/plugin/dapp/autonomy/types/types.go @@ -26,14 +26,14 @@ func init() { types.RegExec(name, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(AutonomyX, "Enable", 0) cfg.RegisterDappFork(AutonomyX, ForkAutonomyDelRule, 0) cfg.RegisterDappFork(AutonomyX, ForkAutonomyEnableItem, 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(AutonomyX, NewType(cfg)) } diff --git a/plugin/dapp/blackwhite/executor/blackwhite.go b/plugin/dapp/blackwhite/executor/blackwhite.go index 4a882bffee..276790c6f0 100644 --- a/plugin/dapp/blackwhite/executor/blackwhite.go +++ b/plugin/dapp/blackwhite/executor/blackwhite.go @@ -30,7 +30,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Blackwhite{})) diff --git a/plugin/dapp/blackwhite/types/types.go b/plugin/dapp/blackwhite/types/types.go index 8fb02dd60d..504f1d99cf 100644 --- a/plugin/dapp/blackwhite/types/types.go +++ b/plugin/dapp/blackwhite/types/types.go @@ -28,13 +28,13 @@ func init() { types.RegExec(BlackwhiteX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(BlackwhiteX, "ForkBlackWhiteV2", 0) cfg.RegisterDappFork(BlackwhiteX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(BlackwhiteX, NewType(cfg)) } diff --git a/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/createERC20.go b/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/createERC20.go index 19165f47da..3fa5c5541c 100644 --- a/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/createERC20.go +++ b/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/createERC20.go @@ -39,7 +39,7 @@ func CreateERC20Cmd() *cobra.Command { return cmd } -//CreateERC20Flags ... +// CreateERC20Flags ... func CreateERC20Flags(cmd *cobra.Command) { cmd.Flags().StringP("key", "k", "", "the deployer private key") _ = cmd.MarkFlagRequired("key") diff --git a/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/deployCrossX2Chain33.go b/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/deployCrossX2Chain33.go index 0e3c9531f5..bd1e45e0a2 100644 --- a/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/deployCrossX2Chain33.go +++ b/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/deployCrossX2Chain33.go @@ -34,7 +34,7 @@ func addCreateCrossBridgeFlags(cmd *cobra.Command) { _ = cmd.MarkFlagRequired("key") cmd.Flags().StringP("note", "n", "", "transaction note info (optional)") cmd.Flags().Float64P("fee", "f", 0, "contract gas fee (optional)") - cmd.Flags().StringP("valset", "r", "", "contruct parameter for valset, as: 'addr, [addr, addr, addr, addr], [25, 25, 25, 25]'") + cmd.Flags().StringP("valset", "r", "", "construct parameter for valset, as: 'addr, [addr, addr, addr, addr], [25, 25, 25, 25]'") _ = cmd.MarkFlagRequired("valset") } @@ -222,8 +222,8 @@ func createOracleTxAndSign(cmd *cobra.Command, from common.Address, valset, ethe } func createValsetTxAndSign(cmd *cobra.Command, from common.Address) (*utils.Chain33OfflineTx, error) { - contructParameter, _ := cmd.Flags().GetString("valset") - createPara := contructParameter + constructParameter, _ := cmd.Flags().GetString("valset") + createPara := constructParameter content, txHash, err := utils.CreateContractAndSign(getTxInfo(cmd), generated.ValsetBin, generated.ValsetABI, createPara, "valset") if nil != err { return nil, err diff --git a/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/multisignSetup.go b/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/multisignSetup.go index 3b670f9c2e..4f53690f12 100644 --- a/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/multisignSetup.go +++ b/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/multisignSetup.go @@ -41,7 +41,7 @@ func SetupOwner(cmd *cobra.Command, _ []string) { BTYAddrChain33 := ebTypes.BTYAddrChain33 parameter := "setup([" - parameter += fmt.Sprintf("%s", owners[0]) + parameter += owners[0] for _, owner := range owners[1:] { parameter += fmt.Sprintf(",%s", owner) } diff --git a/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/multisignTransfer.go b/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/multisignTransfer.go index a3e828d8a2..3edec1dfa2 100644 --- a/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/multisignTransfer.go +++ b/plugin/dapp/bridgevmxgo/boss4x/chain33/offline/multisignTransfer.go @@ -204,7 +204,7 @@ func MultisignTransfer(cmd *cobra.Command, _ []string) { } func getMulSignNonce(mulsign, rpcLaddr string) int64 { - parameter := fmt.Sprintf("nonce()") + parameter := "nonce()" result := chain33Relayer.Query(mulsign, parameter, mulsign, rpcLaddr, gnosis.GnosisSafeABI) if nil == result { diff --git a/plugin/dapp/cert/authority/authority_test.go b/plugin/dapp/cert/authority/authority_test.go index d2fbf50aa2..4fbb4bf0ca 100644 --- a/plugin/dapp/cert/authority/authority_test.go +++ b/plugin/dapp/cert/authority/authority_test.go @@ -79,7 +79,8 @@ func signtxs(priv crypto.PrivKey, cert []byte) { signtx(tx13, priv, cert) } -/** +/* +* 初始化Author实例和userloader */ func initEnv() (*types.Chain33Config, error) { @@ -114,7 +115,8 @@ func initEnv() (*types.Chain33Config, error) { return cfg, nil } -/** +/* +* TestCase01 带证书的交易验签 */ func TestChckSign(t *testing.T) { @@ -128,7 +130,8 @@ func TestChckSign(t *testing.T) { assert.Equal(t, true, tx1.CheckSign(0)) } -/** +/* +* TestCase10 带证书的多交易验签 */ func TestChckSigns(t *testing.T) { @@ -141,13 +144,14 @@ func TestChckSigns(t *testing.T) { for i, tx := range txs { if !tx.CheckSign(0) { - t.Error(fmt.Sprintf("error check tx[%d]", i+1)) + t.Errorf("error check tx[%d]", i+1) return } } } -/** +/* +* TestCase02 带证书的交易并行验签 */ func TestChckSignsPara(t *testing.T) { @@ -166,7 +170,8 @@ func TestChckSignsPara(t *testing.T) { } } -/** +/* +* TestCase03 不带证书,公链签名算法验证 */ func TestChckSignWithNoneAuth(t *testing.T) { @@ -184,7 +189,8 @@ func TestChckSignWithNoneAuth(t *testing.T) { } } -/** +/* +* TestCase04 不带证书,SM2签名验证 */ func TestChckSignWithSm2(t *testing.T) { @@ -209,7 +215,8 @@ func TestChckSignWithSm2(t *testing.T) { } } -/** +/* +* TestCase05 不带证书,secp256r1签名验证 */ func TestChckSignWithEcdsa(t *testing.T) { @@ -233,7 +240,8 @@ func TestChckSignWithEcdsa(t *testing.T) { } } -/** +/* +* TestCase 06 证书检验 */ func TestValidateCert(t *testing.T) { @@ -254,7 +262,8 @@ func TestValidateCert(t *testing.T) { } } -/** +/* +* Testcase07 noneimpl校验器验证(回滚到未开启证书验证的区块使用) */ func TestValidateTxWithNoneAuth(t *testing.T) { @@ -276,7 +285,8 @@ func TestValidateTxWithNoneAuth(t *testing.T) { } } -/** +/* +* Testcase08 重载历史证书 */ func TestReloadCert(t *testing.T) { @@ -298,7 +308,8 @@ func TestReloadCert(t *testing.T) { } } -/** +/* +* Testcase09 根据高度重载历史证书 */ func TestReloadByHeight(t *testing.T) { diff --git a/plugin/dapp/cert/authority/tools/cryptogen/factory/csp/fileks.go b/plugin/dapp/cert/authority/tools/cryptogen/factory/csp/fileks.go index 176f9f318d..06051306c9 100644 --- a/plugin/dapp/cert/authority/tools/cryptogen/factory/csp/fileks.go +++ b/plugin/dapp/cert/authority/tools/cryptogen/factory/csp/fileks.go @@ -82,33 +82,25 @@ func (ks *fileBasedKeyStore) StoreKey(k Key) (err error) { if k == nil { return errors.New("Invalid key. It must be different from nil") } - switch k.(type) { + switch kk := k.(type) { case *ecdsaPrivateKey: - kk := k.(*ecdsaPrivateKey) - err = ks.storePrivateKeyByte(hex.EncodeToString(k.SKI()), kk.privKey) if err != nil { return fmt.Errorf("Failed storing ECDSA private key [%s]", err) } case *ecdsaPublicKey: - kk := k.(*ecdsaPublicKey) - err = ks.storePublicKey(hex.EncodeToString(k.SKI()), kk.pubKey) if err != nil { return fmt.Errorf("Failed storing ECDSA public key [%s]", err) } case *SM2PrivateKey: - kk := k.(*SM2PrivateKey) - err = ks.storePrivateKeyByte(hex.EncodeToString(k.SKI()), kk.PrivKey) if err != nil { return fmt.Errorf("Failed storing SM2 private key [%s]", err) } case *SM2PublicKey: - kk := k.(*SM2PublicKey) - err = ks.storePublicKey(hex.EncodeToString(k.SKI()), kk.PubKey) if err != nil { return fmt.Errorf("Failed storing SM2 public key [%s]", err) diff --git a/plugin/dapp/cert/executor/cert.go b/plugin/dapp/cert/executor/cert.go index 984b202c12..f15962db30 100644 --- a/plugin/dapp/cert/executor/cert.go +++ b/plugin/dapp/cert/executor/cert.go @@ -103,7 +103,8 @@ func (c *Cert) CheckTx(tx *types.Transaction, index int) error { return authority.Author.Validate(tx.GetSignature()) } -/** +/* +* 根据前缀查找证书变更记录,cert回滚、重启、同步用到 */ func (c *Cert) loadHistoryByPrefix() error { @@ -139,7 +140,8 @@ func (c *Cert) loadHistoryByPrefix() error { return ct.ErrGetHistoryCertData } -/** +/* +* 根据具体高度查找变更记录,cert回滚用到 */ func (c *Cert) loadHistoryByHeight() error { diff --git a/plugin/dapp/cert/types/types.go b/plugin/dapp/cert/types/types.go index b6198a35c0..e114f195fd 100644 --- a/plugin/dapp/cert/types/types.go +++ b/plugin/dapp/cert/types/types.go @@ -6,7 +6,7 @@ package types import "github.com/33cn/chain33/types" -//cert +// cert const ( CertActionNew = 1 CertActionUpdate = 2 @@ -23,12 +23,12 @@ func init() { types.RegExec(CertX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(CertX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(CertX, NewType(cfg)) } diff --git a/plugin/dapp/coinsx/commands/coinsx.go b/plugin/dapp/coinsx/commands/coinsx.go index 13b4469e9f..2f7ede98d2 100644 --- a/plugin/dapp/coinsx/commands/coinsx.go +++ b/plugin/dapp/coinsx/commands/coinsx.go @@ -89,7 +89,7 @@ func addManageAccountsFlags(cmd *cobra.Command) { cmd.Flags().Uint32P("op", "o", 0, "modify manager accounts,0:add,1:delete") cmd.MarkFlagRequired("op") - cmd.Flags().StringP("accounts", "a", "", "accounts to modify, seperate with ',' ") + cmd.Flags().StringP("accounts", "a", "", "accounts to modify, separate with ',' ") cmd.MarkFlagRequired("accounts") } diff --git a/plugin/dapp/coinsx/executor/action.go b/plugin/dapp/coinsx/executor/action.go index 63581d0ee0..f5f4a223b8 100644 --- a/plugin/dapp/coinsx/executor/action.go +++ b/plugin/dapp/coinsx/executor/action.go @@ -111,7 +111,7 @@ func (a *action) configTransfer(config *coinTy.TransferFlagConfig) (*types.Recei } -//过滤重复地址 +// 过滤重复地址 func filterAddrs(addrs []string) []string { f := make(map[string]bool) var newAddrs []string @@ -144,7 +144,7 @@ func (a *action) addAccounts(addrs []string) (*types.Receipt, error) { } -//删除掉指定地址 +// 删除掉指定地址 func filterByAddrs(curr, del []string) []string { f := make(map[string]bool) for _, k := range del { @@ -214,7 +214,8 @@ func isManager(addr string, managers []string) bool { } /* - p2p转账受限规则,to执行器也受限制 + p2p转账受限规则,to执行器也受限制 + 1. 超级管理员或者配置了管理员账号 转账不受限 2. 如果未配置转账使能标志或配置为DISABLE,都受限制 3. 配置ENABLE,则不受限 diff --git a/plugin/dapp/coinsx/executor/coinsx.go b/plugin/dapp/coinsx/executor/coinsx.go index 90c3427f1f..f78ddf99b7 100644 --- a/plugin/dapp/coinsx/executor/coinsx.go +++ b/plugin/dapp/coinsx/executor/coinsx.go @@ -40,7 +40,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { setPrefix() } -//InitExecType the initialization process is relatively heavyweight, lots of reflect, so it's global +// InitExecType the initialization process is relatively heavyweight, lots of reflect, so it's global func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Coinsx{})) diff --git a/plugin/dapp/coinsx/types/coinsx.pb.go b/plugin/dapp/coinsx/types/coinsx.pb.go index 30910eb555..65fb02c7d7 100644 --- a/plugin/dapp/coinsx/types/coinsx.pb.go +++ b/plugin/dapp/coinsx/types/coinsx.pb.go @@ -22,7 +22,7 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -//kvmvcc statedb not support 0 value +// kvmvcc statedb not support 0 value type TransferFlag int32 const ( diff --git a/plugin/dapp/coinsx/types/types.go b/plugin/dapp/coinsx/types/types.go index 6715f47638..c265291932 100644 --- a/plugin/dapp/coinsx/types/types.go +++ b/plugin/dapp/coinsx/types/types.go @@ -89,7 +89,7 @@ func (c *CoinsxType) GetTypeMap() map[string]int32 { return actionName } -//DecodePayloadValue 为了性能考虑,coins 是最常用的合约,我们这里不用反射吗,做了特殊化的优化 +// DecodePayloadValue 为了性能考虑,coins 是最常用的合约,我们这里不用反射吗,做了特殊化的优化 func (c *CoinsxType) DecodePayloadValue(tx *types.Transaction) (string, reflect.Value, error) { name, value, err := c.decodePayloadValue(tx) return name, value, err diff --git a/plugin/dapp/collateralize/commands/cmd.go b/plugin/dapp/collateralize/commands/cmd.go index 3716625b8f..1db87cbced 100644 --- a/plugin/dapp/collateralize/commands/cmd.go +++ b/plugin/dapp/collateralize/commands/cmd.go @@ -49,7 +49,7 @@ func addCollateralizeCreateFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("balance") } -//CollateralizeCreate ... +// CollateralizeCreate ... func CollateralizeCreate(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") paraName, _ := cmd.Flags().GetString("paraName") @@ -84,7 +84,7 @@ func addCollateralizeBorrowFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("value") } -//CollateralizeBorrow ... +// CollateralizeBorrow ... func CollateralizeBorrow(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") paraName, _ := cmd.Flags().GetString("paraName") @@ -122,7 +122,7 @@ func addCollateralizeAppendFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("value") } -//CollateralizeAppend ... +// CollateralizeAppend ... func CollateralizeAppend(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") paraName, _ := cmd.Flags().GetString("paraName") @@ -159,7 +159,7 @@ func addCollateralizeRepayFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("recordID") } -//CollateralizeRepay ... +// CollateralizeRepay ... func CollateralizeRepay(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") paraName, _ := cmd.Flags().GetString("paraName") @@ -195,7 +195,7 @@ func addCollateralizePriceFeedFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("volume") } -//CollateralizePriceFeed ... +// CollateralizePriceFeed ... func CollateralizePriceFeed(cmd *cobra.Command, args []string) { paraName, _ := cmd.Flags().GetString("paraName") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") @@ -231,7 +231,7 @@ func addCollateralizeRetrieveFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("balance") } -//CollateralizeRetrieve ... +// CollateralizeRetrieve ... func CollateralizeRetrieve(cmd *cobra.Command, args []string) { paraName, _ := cmd.Flags().GetString("paraName") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") @@ -268,7 +268,7 @@ func addCollateralizeManageFlags(cmd *cobra.Command) { cmd.Flags().Float64P("totalBalance", "t", 0, "totalBalance") } -//CollateralizeManage ... +// CollateralizeManage ... func CollateralizeManage(cmd *cobra.Command, args []string) { paraName, _ := cmd.Flags().GetString("paraName") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") @@ -290,7 +290,7 @@ func CollateralizeManage(cmd *cobra.Command, args []string) { ctx.RunWithoutMarshal() } -//CollateralizeQueryCfgCmd ... +// CollateralizeQueryCfgCmd ... func CollateralizeQueryCfgCmd() *cobra.Command { cmd := &cobra.Command{ Use: "config", @@ -300,7 +300,7 @@ func CollateralizeQueryCfgCmd() *cobra.Command { return cmd } -//CollateralizeQueryConfig ... +// CollateralizeQueryConfig ... func CollateralizeQueryConfig(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") @@ -313,7 +313,7 @@ func CollateralizeQueryConfig(cmd *cobra.Command, args []string) { ctx.Run() } -//CollateralizeQueryPriceCmd ... +// CollateralizeQueryPriceCmd ... func CollateralizeQueryPriceCmd() *cobra.Command { cmd := &cobra.Command{ Use: "price", @@ -323,7 +323,7 @@ func CollateralizeQueryPriceCmd() *cobra.Command { return cmd } -//CollateralizeQueryPrice ... +// CollateralizeQueryPrice ... func CollateralizeQueryPrice(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") @@ -336,7 +336,7 @@ func CollateralizeQueryPrice(cmd *cobra.Command, args []string) { ctx.Run() } -//CollateralizeQueryUserBalanceCmd ... +// CollateralizeQueryUserBalanceCmd ... func CollateralizeQueryUserBalanceCmd() *cobra.Command { cmd := &cobra.Command{ Use: "balance", @@ -352,7 +352,7 @@ func addCollateralizeQueryBalanceFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("address") } -//CollateralizeQueryUserBalance ... +// CollateralizeQueryUserBalance ... func CollateralizeQueryUserBalance(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") addr, _ := cmd.Flags().GetString("address") @@ -395,7 +395,7 @@ func addCollateralizeQueryFlags(cmd *cobra.Command) { cmd.Flags().StringP("borrowID", "b", "", "borrow ID") } -//CollateralizeQuery ... +// CollateralizeQuery ... func CollateralizeQuery(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") collateralizeID, _ := cmd.Flags().GetString("collateralizeID") diff --git a/plugin/dapp/collateralize/executor/collateralize.go b/plugin/dapp/collateralize/executor/collateralize.go index e35a1fcbde..d7d8c3f20c 100644 --- a/plugin/dapp/collateralize/executor/collateralize.go +++ b/plugin/dapp/collateralize/executor/collateralize.go @@ -14,7 +14,7 @@ import ( var clog = log.New("module", "execs.collateralize") var driverName = pty.CollateralizeX -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Collateralize{})) diff --git a/plugin/dapp/collateralize/executor/collateralizedb.go b/plugin/dapp/collateralize/executor/collateralizedb.go index 2ad8d6cf48..011058cb22 100644 --- a/plugin/dapp/collateralize/executor/collateralizedb.go +++ b/plugin/dapp/collateralize/executor/collateralizedb.go @@ -28,7 +28,7 @@ const ( MaxCount = int32(100) // 最多取100条 ) -//setting +// setting const ( DefaultDebtCeiling = 10000 // 默认借贷限额 DefaultLiquidationRatio = 0.4 * 1e4 // 默认质押比 @@ -66,19 +66,19 @@ func Key(id string) (key []byte) { return key } -//ConfigKey Key for CollateralizeConfig +// ConfigKey Key for CollateralizeConfig func ConfigKey() (key []byte) { key = append(key, []byte("mavl-"+pty.CollateralizeX+"-config")...) return key } -//AddrKey Key for CollateralizeAddrConfig +// AddrKey Key for CollateralizeAddrConfig func AddrKey() (key []byte) { key = append(key, []byte("mavl-"+issuanceE.IssuanceX+"-addr")...) return key } -//PriceKey Key for IssuancePriceFeed +// PriceKey Key for IssuancePriceFeed func PriceKey() (key []byte) { key = append(key, []byte("mavl-"+pty.CollateralizeX+"-price")...) return key diff --git a/plugin/dapp/collateralize/executor/query.go b/plugin/dapp/collateralize/executor/query.go index 740682e387..f8fed9a046 100644 --- a/plugin/dapp/collateralize/executor/query.go +++ b/plugin/dapp/collateralize/executor/query.go @@ -9,7 +9,7 @@ import ( pty "github.com/33cn/plugin/plugin/dapp/collateralize/types" ) -//Query_CollateralizeInfoByID ... +// Query_CollateralizeInfoByID ... func (c *Collateralize) Query_CollateralizeInfoByID(req *pty.ReqCollateralizeInfo) (types.Message, error) { coll, err := queryCollateralizeByID(c.GetStateDB(), req.CollateralizeId) if err != nil { @@ -35,7 +35,7 @@ func (c *Collateralize) Query_CollateralizeInfoByID(req *pty.ReqCollateralizeInf return info, nil } -//Query_CollateralizeInfoByIDs ... +// Query_CollateralizeInfoByIDs ... func (c *Collateralize) Query_CollateralizeInfoByIDs(req *pty.ReqCollateralizeInfos) (types.Message, error) { infos := &pty.RepCollateralizeCurrentInfos{} for _, id := range req.CollateralizeIds { @@ -66,7 +66,7 @@ func (c *Collateralize) Query_CollateralizeInfoByIDs(req *pty.ReqCollateralizeIn return infos, nil } -//Query_CollateralizeByStatus ... +// Query_CollateralizeByStatus ... func (c *Collateralize) Query_CollateralizeByStatus(req *pty.ReqCollateralizeByStatus) (types.Message, error) { ids := &pty.RepCollateralizeIDs{} collIDRecords, err := queryCollateralizeByStatus(c.GetLocalDB(), req.Status, req.CollID) @@ -79,7 +79,7 @@ func (c *Collateralize) Query_CollateralizeByStatus(req *pty.ReqCollateralizeByS return ids, nil } -//Query_CollateralizeByAddr ... +// Query_CollateralizeByAddr ... func (c *Collateralize) Query_CollateralizeByAddr(req *pty.ReqCollateralizeByAddr) (types.Message, error) { ids := &pty.RepCollateralizeIDs{} collIDRecords, err := queryCollateralizeByAddr(c.GetLocalDB(), req.Addr, req.Status, req.CollID) @@ -92,7 +92,7 @@ func (c *Collateralize) Query_CollateralizeByAddr(req *pty.ReqCollateralizeByAdd return ids, nil } -//Query_CollateralizeRecordByID ... +// Query_CollateralizeRecordByID ... func (c *Collateralize) Query_CollateralizeRecordByID(req *pty.ReqCollateralizeRecord) (types.Message, error) { ret := &pty.RepCollateralizeRecord{} issuRecord, err := queryCollateralizeRecordByID(c.GetStateDB(), req.CollateralizeId, req.RecordId) @@ -105,7 +105,7 @@ func (c *Collateralize) Query_CollateralizeRecordByID(req *pty.ReqCollateralizeR return ret, nil } -//Query_CollateralizeRecordByAddr ... +// Query_CollateralizeRecordByAddr ... func (c *Collateralize) Query_CollateralizeRecordByAddr(req *pty.ReqCollateralizeRecordByAddr) (types.Message, error) { ret := &pty.RepCollateralizeRecords{} records, err := queryCollateralizeRecordByAddr(c.GetStateDB(), c.GetLocalDB(), req.Addr, req.Status, req.CollateralizeId, req.RecordId) @@ -126,7 +126,7 @@ func (c *Collateralize) Query_CollateralizeRecordByAddr(req *pty.ReqCollateraliz return ret, nil } -//Query_CollateralizeRecordByStatus ... +// Query_CollateralizeRecordByStatus ... func (c *Collateralize) Query_CollateralizeRecordByStatus(req *pty.ReqCollateralizeRecordByStatus) (types.Message, error) { ret := &pty.RepCollateralizeRecords{} records, err := queryCollateralizeRecordByStatus(c.GetStateDB(), c.GetLocalDB(), req.Status, req.CollateralizeId, req.RecordId) @@ -139,7 +139,7 @@ func (c *Collateralize) Query_CollateralizeRecordByStatus(req *pty.ReqCollateral return ret, nil } -//Query_CollateralizeConfig ... +// Query_CollateralizeConfig ... func (c *Collateralize) Query_CollateralizeConfig(req *pty.ReqCollateralizeRecordByAddr) (types.Message, error) { config, err := getCollateralizeConfig(c.GetStateDB()) if err != nil { @@ -166,7 +166,7 @@ func (c *Collateralize) Query_CollateralizeConfig(req *pty.ReqCollateralizeRecor return ret, nil } -//Query_CollateralizePrice ... +// Query_CollateralizePrice ... func (c *Collateralize) Query_CollateralizePrice(req *pty.ReqCollateralizeRecordByAddr) (types.Message, error) { price, err := getLatestPrice(c.GetStateDB()) if err != nil { @@ -177,7 +177,7 @@ func (c *Collateralize) Query_CollateralizePrice(req *pty.ReqCollateralizeRecord return &pty.RepCollateralizePrice{Price: price}, nil } -//Query_CollateralizeUserBalance ... +// Query_CollateralizeUserBalance ... func (c *Collateralize) Query_CollateralizeUserBalance(req *pty.ReqCollateralizeRecordByAddr) (types.Message, error) { balance, err := queryCollateralizeUserBalance(c.GetStateDB(), c.GetLocalDB(), req.Addr) if err != nil { diff --git a/plugin/dapp/collateralize/types/collateralize.go b/plugin/dapp/collateralize/types/collateralize.go index 0813942ba7..d508f8d574 100644 --- a/plugin/dapp/collateralize/types/collateralize.go +++ b/plugin/dapp/collateralize/types/collateralize.go @@ -26,14 +26,14 @@ func init() { types.RegExec(CollateralizeX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(CollateralizeX, "Enable", 0) cfg.RegisterDappFork(CollateralizeX, ForkCollateralizeTableUpdate, 0) cfg.RegisterDappFork(CollateralizeX, ForkCollateralizePrecision, 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(CollateralizeX, NewType(cfg)) } diff --git a/plugin/dapp/collateralize/types/table.go b/plugin/dapp/collateralize/types/table.go index 8c9f3c2561..4ff670e44b 100644 --- a/plugin/dapp/collateralize/types/table.go +++ b/plugin/dapp/collateralize/types/table.go @@ -16,7 +16,7 @@ var opt = &table.Option{ Index: []string{"status", "addr", "addr_status"}, } -//NewCollateralizeTable 新建表 +// NewCollateralizeTable 新建表 func NewCollateralizeTable(kvdb db.KV) *table.Table { rowmeta := NewCollatetalizeRow() table, err := table.NewTable(rowmeta, kvdb, opt) @@ -26,22 +26,22 @@ func NewCollateralizeTable(kvdb db.KV) *table.Table { return table } -//CollatetalizeRow table meta 结构 +// CollatetalizeRow table meta 结构 type CollatetalizeRow struct { *ReceiptCollateralize } -//NewCollatetalizeRow 新建一个meta 结构 +// NewCollatetalizeRow 新建一个meta 结构 func NewCollatetalizeRow() *CollatetalizeRow { return &CollatetalizeRow{ReceiptCollateralize: &ReceiptCollateralize{}} } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (tx *CollatetalizeRow) CreateRow() *table.Row { return &table.Row{Data: &ReceiptCollateralize{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (tx *CollatetalizeRow) SetPayload(data types.Message) error { if txdata, ok := data.(*ReceiptCollateralize); ok { tx.ReceiptCollateralize = txdata @@ -50,7 +50,7 @@ func (tx *CollatetalizeRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (tx *CollatetalizeRow) Get(key string) ([]byte, error) { if key == "collateralizeid" { return []byte(tx.CollateralizeId), nil @@ -81,22 +81,22 @@ func NewRecordTable(kvdb db.KV) *table.Table { return table } -//CollateralizeRecordRow table meta 结构 +// CollateralizeRecordRow table meta 结构 type CollateralizeRecordRow struct { *ReceiptCollateralize } -//NewRecordRow 新建一个meta 结构 +// NewRecordRow 新建一个meta 结构 func NewRecordRow() *CollateralizeRecordRow { return &CollateralizeRecordRow{ReceiptCollateralize: &ReceiptCollateralize{}} } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (tx *CollateralizeRecordRow) CreateRow() *table.Row { return &table.Row{Data: &ReceiptCollateralize{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (tx *CollateralizeRecordRow) SetPayload(data types.Message) error { if txdata, ok := data.(*ReceiptCollateralize); ok { tx.ReceiptCollateralize = txdata @@ -105,7 +105,7 @@ func (tx *CollateralizeRecordRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (tx *CollateralizeRecordRow) Get(key string) ([]byte, error) { if key == "borrowid" { return []byte(tx.RecordId), nil diff --git a/plugin/dapp/collateralize/types/types.go b/plugin/dapp/collateralize/types/types.go index c1c2c71608..c4dbf606fe 100644 --- a/plugin/dapp/collateralize/types/types.go +++ b/plugin/dapp/collateralize/types/types.go @@ -4,7 +4,7 @@ package types -//Collateralize op +// Collateralize op const ( CollateralizeActionCreate = 1 + iota CollateralizeActionBorrow @@ -30,7 +30,7 @@ const ( CollateralizePreLiquidationRatio = 1.1 * 1e4 //TODO 预清算比例,抵押物价值跌到借出ccny价值110%的时候开始清算 ) -//Collateralize status +// Collateralize status const ( CollateralizeStatusCreated = 1 + iota CollateralizeStatusClose @@ -43,7 +43,7 @@ const ( // CollateralizeAssetTypeEth //) -//collater ... +// collater ... const ( CollateralizeUserStatusCreate = 1 + iota CollateralizeUserStatusWarning @@ -53,7 +53,7 @@ const ( CollateralizeUserStatusClose ) -//fork ... +// fork ... var ( ForkCollateralizeTableUpdate = "ForkCollateralizeTableUpdate" ForkCollateralizePrecision = "ForkCollateralizePrecision" diff --git a/plugin/dapp/cross2eth/boss4x/chain33/offline/createERC20.go b/plugin/dapp/cross2eth/boss4x/chain33/offline/createERC20.go index 393dc8937a..e382ce83c4 100644 --- a/plugin/dapp/cross2eth/boss4x/chain33/offline/createERC20.go +++ b/plugin/dapp/cross2eth/boss4x/chain33/offline/createERC20.go @@ -41,7 +41,7 @@ func CreateERC20Cmd() *cobra.Command { return cmd } -//CreateERC20Flags ... +// CreateERC20Flags ... func CreateERC20Flags(cmd *cobra.Command) { cmd.Flags().StringP("key", "k", "", "the deployer private key") _ = cmd.MarkFlagRequired("key") diff --git a/plugin/dapp/cross2eth/boss4x/chain33/offline/deployCrossX2Chain33.go b/plugin/dapp/cross2eth/boss4x/chain33/offline/deployCrossX2Chain33.go index bd2e2d27cf..35fed15f80 100644 --- a/plugin/dapp/cross2eth/boss4x/chain33/offline/deployCrossX2Chain33.go +++ b/plugin/dapp/cross2eth/boss4x/chain33/offline/deployCrossX2Chain33.go @@ -97,7 +97,7 @@ func addCreateCrossBridgeFlags(cmd *cobra.Command) { _ = cmd.MarkFlagRequired("key") cmd.Flags().StringP("note", "n", "", "transaction note info (optional)") cmd.Flags().Float64P("fee", "f", 0, "contract gas fee (optional)") - cmd.Flags().StringP("valset", "r", "", "contruct parameter for valset, as: 'addr, [addr, addr, addr, addr], [25, 25, 25, 25]'") + cmd.Flags().StringP("valset", "r", "", "construct parameter for valset, as: 'addr, [addr, addr, addr, addr], [25, 25, 25, 25]'") _ = cmd.MarkFlagRequired("valset") cmd.Flags().StringP("multisignAddrs", "m", "", "multisign address, as: 'addr, addr, addr, addr'") _ = cmd.MarkFlagRequired("multisignAddrs") @@ -375,7 +375,7 @@ func multisignSetup(txCreateInfo *utils.TxCreateInfo, multisignAddrs string, mul BTYAddrChain33 := ebTypes.BTYAddrChain33 parameter := "setup([" - parameter += fmt.Sprintf("%s", owners[0]) + parameter += owners[0] for _, owner := range owners[1:] { parameter += fmt.Sprintf(",%s", owner) } diff --git a/plugin/dapp/cross2eth/boss4x/chain33/offline/multisignTransfer.go b/plugin/dapp/cross2eth/boss4x/chain33/offline/multisignTransfer.go index 373f48878d..36c7f77f06 100644 --- a/plugin/dapp/cross2eth/boss4x/chain33/offline/multisignTransfer.go +++ b/plugin/dapp/cross2eth/boss4x/chain33/offline/multisignTransfer.go @@ -202,7 +202,7 @@ func MultisignTransfer(cmd *cobra.Command, _ []string) { } func getMulSignNonce(mulsign, rpcLaddr string) int64 { - parameter := fmt.Sprintf("nonce()") + parameter := "nonce()" result := chain33Relayer.Query(mulsign, parameter, mulsign, rpcLaddr, generated.GnosisSafeABI) if nil == result { diff --git a/plugin/dapp/cross2eth/boss4x/chain33/offline/offline.go b/plugin/dapp/cross2eth/boss4x/chain33/offline/offline.go index 13debc1404..60830c6182 100644 --- a/plugin/dapp/cross2eth/boss4x/chain33/offline/offline.go +++ b/plugin/dapp/cross2eth/boss4x/chain33/offline/offline.go @@ -154,5 +154,4 @@ func InitCfg(filepath string, cfg interface{}) { fmt.Println(err) os.Exit(-1) } - return } diff --git a/plugin/dapp/cross2eth/boss4x/ethereum/offline/cfgLockedToken.go b/plugin/dapp/cross2eth/boss4x/ethereum/offline/cfgLockedToken.go index 8d42298d6a..eb9c55d3e8 100644 --- a/plugin/dapp/cross2eth/boss4x/ethereum/offline/cfgLockedToken.go +++ b/plugin/dapp/cross2eth/boss4x/ethereum/offline/cfgLockedToken.go @@ -29,7 +29,7 @@ func ConfigLockedTokenOfflineSaveCmd() *cobra.Command { return cmd } -//ConfigLockedTokenOfflineSaveFlags ... +// ConfigLockedTokenOfflineSaveFlags ... func ConfigLockedTokenOfflineSaveFlags(cmd *cobra.Command) { cmd.Flags().StringP("token", "t", "", "token addr") //_ = cmd.MarkFlagRequired("token") diff --git a/plugin/dapp/cross2eth/boss4x/ethereum/offline/deployCrossX2Eth.go b/plugin/dapp/cross2eth/boss4x/ethereum/offline/deployCrossX2Eth.go index 3c91c6e1cb..122567ed84 100644 --- a/plugin/dapp/cross2eth/boss4x/ethereum/offline/deployCrossX2Eth.go +++ b/plugin/dapp/cross2eth/boss4x/ethereum/offline/deployCrossX2Eth.go @@ -353,7 +353,7 @@ func NewTxWrite(infos []*DeployInfo, deployerAddr common.Address, url, fileName return nil } -//deploy contract step 1 +// deploy contract step 1 func deployValSetPackData(validators []common.Address, powers []*big.Int, deployerAddr common.Address) ([]byte, error) { parsed, err := abi.JSON(strings.NewReader(generated.ValsetABI)) if err != nil { @@ -367,7 +367,7 @@ func deployValSetPackData(validators []common.Address, powers []*big.Int, deploy return append(bin, packdata...), nil } -//deploy contract step 2 +// deploy contract step 2 func deploychain33BridgePackData(deployerAddr, valSetAddr common.Address) ([]byte, error) { parsed, err := abi.JSON(strings.NewReader(generated.Chain33BridgeABI)) if err != nil { @@ -381,7 +381,7 @@ func deploychain33BridgePackData(deployerAddr, valSetAddr common.Address) ([]byt return append(bin, input...), nil } -//deploy contract step 3 +// deploy contract step 3 func deployOraclePackData(deployerAddr, valSetAddr, bridgeAddr common.Address) ([]byte, error) { parsed, err := abi.JSON(strings.NewReader(generated.OracleABI)) if err != nil { @@ -395,7 +395,7 @@ func deployOraclePackData(deployerAddr, valSetAddr, bridgeAddr common.Address) ( return append(bin, packData...), nil } -//deploy contract step 4 +// deploy contract step 4 func deployBridgeBankPackData(deployerAddr, bridgeAddr, oracalAddr common.Address) ([]byte, error) { parsed, err := abi.JSON(strings.NewReader(generated.BridgeBankABI)) if err != nil { @@ -409,7 +409,7 @@ func deployBridgeBankPackData(deployerAddr, bridgeAddr, oracalAddr common.Addres return append(bin, packData...), nil } -////deploy contract step 5 +// //deploy contract step 5 func callSetBridgeBank(bridgeBankAddr common.Address) ([]byte, error) { method := "setBridgeBank" parsed, err := abi.JSON(strings.NewReader(generated.Chain33BridgeABI)) @@ -423,7 +423,7 @@ func callSetBridgeBank(bridgeBankAddr common.Address) ([]byte, error) { return packData, nil } -//deploy contract step 6 +// deploy contract step 6 func callSetOracal(oracalAddr common.Address) ([]byte, error) { method := "setOracle" parsed, err := abi.JSON(strings.NewReader(generated.Chain33BridgeABI)) @@ -437,7 +437,7 @@ func callSetOracal(oracalAddr common.Address) ([]byte, error) { return packData, nil } -//deploy contract step 7 +// deploy contract step 7 func deployBridgeRegistry(chain33BridgeAddr, bridgeBankAddr, oracleAddr, valSetAddr common.Address) ([]byte, error) { parsed, err := abi.JSON(strings.NewReader(generated.BridgeRegistryABI)) if err != nil { @@ -451,7 +451,7 @@ func deployBridgeRegistry(chain33BridgeAddr, bridgeBankAddr, oracleAddr, valSetA return append(bin, packData...), nil } -//step 8 +// step 8 func setSymbol(symbol string) ([]byte, error) { bridgeAbi, err := abi.JSON(strings.NewReader(generated.BridgeBankABI)) if err != nil { @@ -464,7 +464,7 @@ func setSymbol(symbol string) ([]byte, error) { return abiData, nil } -//step 10 +// step 10 func offlineSaveAccount(multisignContract common.Address) ([]byte, error) { bridgeAbi, err := abi.JSON(strings.NewReader(generated.BridgeBankABI)) if err != nil { @@ -478,7 +478,7 @@ func offlineSaveAccount(multisignContract common.Address) ([]byte, error) { return abiData, nil } -//step 11 +// step 11 func multisignSetup(multisigns []common.Address) ([]byte, error) { AddressZero := common.HexToAddress(ebTypes.EthNilAddr) gnoAbi, err := abi.JSON(strings.NewReader(gnosis.GnosisSafeABI)) diff --git a/plugin/dapp/cross2eth/boss4x/ethereum/offline/offline.go b/plugin/dapp/cross2eth/boss4x/ethereum/offline/offline.go index a85b395e81..fc94f9822f 100644 --- a/plugin/dapp/cross2eth/boss4x/ethereum/offline/offline.go +++ b/plugin/dapp/cross2eth/boss4x/ethereum/offline/offline.go @@ -181,5 +181,4 @@ func InitCfg(filepath string, cfg interface{}) { fmt.Println(err) os.Exit(-1) } - return } diff --git a/plugin/dapp/cross2eth/boss4x/ethereum/offline/safeTransferCmd.go b/plugin/dapp/cross2eth/boss4x/ethereum/offline/safeTransferCmd.go index 460726f555..823c94a310 100644 --- a/plugin/dapp/cross2eth/boss4x/ethereum/offline/safeTransferCmd.go +++ b/plugin/dapp/cross2eth/boss4x/ethereum/offline/safeTransferCmd.go @@ -203,7 +203,7 @@ func addPreliminarySignMultisignTransferTxFlag(cmd *cobra.Command) { _ = cmd.MarkFlagRequired("keys") } -//签名交易 +// 签名交易 func preliminarySignMultisignTransferTx(cmd *cobra.Command, _ []string) { txFilePath, _ := cmd.Flags().GetString("file") keys, _ := cmd.Flags().GetString("keys") diff --git a/plugin/dapp/cross2eth/contracts/test/bridgeBank_test.go b/plugin/dapp/cross2eth/contracts/test/bridgeBank_test.go index 755759f5be..841bf87c51 100644 --- a/plugin/dapp/cross2eth/contracts/test/bridgeBank_test.go +++ b/plugin/dapp/cross2eth/contracts/test/bridgeBank_test.go @@ -22,7 +22,7 @@ import ( "github.com/stretchr/testify/require" ) -//"BridgeToken creation (Chain33 assets)" +// "BridgeToken creation (Chain33 assets)" func TestBrigeTokenCreat(t *testing.T) { ctx := context.Background() println("TEST:BridgeToken creation (Chain33 assets)") @@ -109,11 +109,11 @@ func TestBrigeTokenCreat(t *testing.T) { } } -//测试在chain33上锁定资产,然后在以太坊上铸币 -//发行token="BTY" -//铸币NewOracleClaim -//铸币成功 -//Bridge token minting (for locked chain33 assets) +// 测试在chain33上锁定资产,然后在以太坊上铸币 +// 发行token="BTY" +// 铸币NewOracleClaim +// 铸币成功 +// Bridge token minting (for locked chain33 assets) func TestBrigeTokenMint(t *testing.T) { ctx := context.Background() println("TEST:BridgeToken creation (Chain33 assets)") @@ -232,8 +232,8 @@ func TestBrigeTokenMint(t *testing.T) { t.Logf("The minted amount is:%d", balance.Int64()) } -//测试在以太坊上lock数字资产,包括Eth和Erc20 -//Bridge deposit locking (deposit erc20/eth assets) +// 测试在以太坊上lock数字资产,包括Eth和Erc20 +// Bridge deposit locking (deposit erc20/eth assets) func TestBridgeDepositLock(t *testing.T) { ctx := context.Background() println("TEST:Bridge deposit locking (Erc20/Eth assets)") @@ -338,10 +338,10 @@ func TestBridgeDepositLock(t *testing.T) { t.Logf("eth bridgeBankBalance changes to:%d", bridgeBankBalance.Int64()) } -//测试在以太坊上unlock数字资产,包括Eth和Erc20, -//即从chain33取回在eth上发行的的ETH或ERC20数字资产,之前通过lock操作发送到了chain33 -//现在则通过NewProphecyClaim 的burn操作将数字资产取回 -//Ethereum/ERC20 token unlocking (for burned chain33 assets) +// 测试在以太坊上unlock数字资产,包括Eth和Erc20, +// 即从chain33取回在eth上发行的的ETH或ERC20数字资产,之前通过lock操作发送到了chain33 +// 现在则通过NewProphecyClaim 的burn操作将数字资产取回 +// Ethereum/ERC20 token unlocking (for burned chain33 assets) func TestBridgeBankUnlock(t *testing.T) { ctx := context.Background() println("TEST:Ethereum/ERC20 token unlocking (for burned chain33 assets)") @@ -490,8 +490,8 @@ func TestBridgeBankUnlock(t *testing.T) { require.Equal(t, userUSDTbalance.Int64(), newProphecyAmount) } -//测试在以太坊上多次unlock数字资产Eth -//Ethereum/ERC20 token second unlocking (for burned chain33 assets) +// 测试在以太坊上多次unlock数字资产Eth +// Ethereum/ERC20 token second unlocking (for burned chain33 assets) func TestBridgeBankSecondUnlockEth(t *testing.T) { ctx := context.Background() println("TEST:to be unlocked incrementally by successive burn prophecies (for burned chain33 assets)") @@ -638,8 +638,8 @@ func TestBridgeBankSecondUnlockEth(t *testing.T) { require.Equal(t, userEthbalance.Int64()+newProphecyAmountSecond, userEthbalanceAfter.Int64()) } -//测试在以太坊上多次unlock数字资产Erc20 -//Ethereum/ERC20 token unlocking (for burned chain33 assets) +// 测试在以太坊上多次unlock数字资产Erc20 +// Ethereum/ERC20 token unlocking (for burned chain33 assets) func TestBridgeBankSedondUnlockErc20(t *testing.T) { ctx := context.Background() println("TEST:ERC20 to be unlocked incrementally by successive burn prophecies (for burned chain33 assets))") diff --git a/plugin/dapp/cross2eth/contracts/test/setup/setupTestEnv.go b/plugin/dapp/cross2eth/contracts/test/setup/setupTestEnv.go index 66a19f8824..8a6849994c 100644 --- a/plugin/dapp/cross2eth/contracts/test/setup/setupTestEnv.go +++ b/plugin/dapp/cross2eth/contracts/test/setup/setupTestEnv.go @@ -19,7 +19,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" ) -//PrepareTestEnv ... +// PrepareTestEnv ... func PrepareTestEnv() (*ethinterface.SimExtend, *ethtxs.DeployPara) { genesiskey, _ := crypto.GenerateKey() alloc := make(core.GenesisAlloc) @@ -61,7 +61,7 @@ func PrepareTestEnv() (*ethinterface.SimExtend, *ethtxs.DeployPara) { return sim, para } -//DeployContracts ... +// DeployContracts ... func DeployContracts() (*ethtxs.DeployPara, *ethinterface.SimExtend, *ethtxs.X2EthContracts, *ethtxs.X2EthDeployInfo, error) { ctx := context.Background() sim, para := PrepareTestEnv() @@ -90,7 +90,7 @@ func DeployContracts() (*ethtxs.DeployPara, *ethinterface.SimExtend, *ethtxs.X2E return para, sim, x2EthContracts, x2EthDeployInfo, nil } -//DeployValset : 部署Valset +// DeployValset : 部署Valset func DeployValset(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer common.Address, operator common.Address, initValidators []common.Address, initPowers []*big.Int) (*generated.Valset, *ethtxs.DeployResult, error) { auth, err := ethtxs.PrepareAuth(client, privateKey, deployer) if nil != err { @@ -111,7 +111,7 @@ func DeployValset(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKe return valset, deployResult, nil } -//DeployChain33Bridge : 部署Chain33Bridge +// DeployChain33Bridge : 部署Chain33Bridge func DeployChain33Bridge(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer common.Address, operator, valset common.Address) (*generated.Chain33Bridge, *ethtxs.DeployResult, error) { auth, err := ethtxs.PrepareAuth(client, privateKey, deployer) if nil != err { @@ -131,7 +131,7 @@ func DeployChain33Bridge(client ethinterface.EthClientSpec, privateKey *ecdsa.Pr return chain33Bridge, deployResult, nil } -//DeployOracle : 部署Oracle +// DeployOracle : 部署Oracle func DeployOracle(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer, operator, valset, chain33Bridge common.Address) (*generated.Oracle, *ethtxs.DeployResult, error) { auth, err := ethtxs.PrepareAuth(client, privateKey, deployer) if nil != err { @@ -151,7 +151,7 @@ func DeployOracle(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKe return oracle, deployResult, nil } -//DeployBridgeBank : 部署BridgeBank +// DeployBridgeBank : 部署BridgeBank func DeployBridgeBank(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer, operator, oracle, chain33Bridge common.Address) (*generated.BridgeBank, *ethtxs.DeployResult, error) { auth, err := ethtxs.PrepareAuth(client, privateKey, deployer) if nil != err { @@ -171,7 +171,7 @@ func DeployBridgeBank(client ethinterface.EthClientSpec, privateKey *ecdsa.Priva return bridgeBank, deployResult, nil } -//DeployBridgeRegistry : 部署BridgeRegistry +// DeployBridgeRegistry : 部署BridgeRegistry func DeployBridgeRegistry(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer, chain33BridgeAddr, bridgeBankAddr, oracleAddr, valsetAddr common.Address) (*generated.BridgeRegistry, *ethtxs.DeployResult, error) { auth, err := ethtxs.PrepareAuth(client, privateKey, deployer) if nil != err { @@ -191,7 +191,7 @@ func DeployBridgeRegistry(client ethinterface.EthClientSpec, privateKey *ecdsa.P return bridgeRegistry, deployResult, nil } -//DeployAndInit ... +// DeployAndInit ... func DeployAndInit(client ethinterface.EthClientSpec, para *ethtxs.DeployPara) (*ethtxs.X2EthContracts, *ethtxs.X2EthDeployInfo, error) { x2EthContracts := ðtxs.X2EthContracts{} deployInfo := ðtxs.X2EthDeployInfo{} diff --git a/plugin/dapp/cross2eth/ebcli/chain33RelayerCmd.go b/plugin/dapp/cross2eth/ebcli/chain33RelayerCmd.go index e518f1024b..2fb4fbd9f7 100644 --- a/plugin/dapp/cross2eth/ebcli/chain33RelayerCmd.go +++ b/plugin/dapp/cross2eth/ebcli/chain33RelayerCmd.go @@ -10,7 +10,7 @@ import ( "github.com/spf13/cobra" ) -//Chain33RelayerCmd RelayerCmd command func +// Chain33RelayerCmd RelayerCmd command func func Chain33RelayerCmd() *cobra.Command { cmd := &cobra.Command{ Use: "chain33 ", @@ -37,7 +37,7 @@ func Chain33RelayerCmd() *cobra.Command { return cmd } -//TokenAddressCmd... +// TokenAddressCmd... func TokenAddressCmd() *cobra.Command { cmd := &cobra.Command{ Use: "token", @@ -60,7 +60,7 @@ func ShowTokenAddressCmd() *cobra.Command { return cmd } -//SetTokenFlags ... +// SetTokenFlags ... func ShowTokenFlags(cmd *cobra.Command) { cmd.Flags().StringP("symbol", "s", "", "token symbol(optional), if not set,show all the token") } @@ -88,7 +88,7 @@ func ShowBridgeRegistryAddr4chain33Cmd() *cobra.Command { return cmd } -//ShowBridgeRegistryAddr ... +// ShowBridgeRegistryAddr ... func ShowBridgeRegistryAddr4chain33(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") var res ebTypes.ReplyAddr @@ -106,7 +106,7 @@ func simBurnFromEthCmd() *cobra.Command { return cmd } -//SimBurnFlags ... +// SimBurnFlags ... func SimBurnFlags(cmd *cobra.Command) { cmd.Flags().StringP("key", "k", "", "Ethereum sender address") _ = cmd.MarkFlagRequired("key") @@ -148,7 +148,7 @@ func simLockFromEthCmd() *cobra.Command { return cmd } -//LockEthErc20AssetFlags ... +// LockEthErc20AssetFlags ... func simLockEthErc20AssetFlags(cmd *cobra.Command) { cmd.Flags().StringP("key", "k", "", "Ethereum sender address") _ = cmd.MarkFlagRequired("key") @@ -179,7 +179,7 @@ func simLockFromEth(cmd *cobra.Command, args []string) { ctx.Run() } -//LockAsyncCmd ... +// LockAsyncCmd ... func LockAsyncFromChain33Cmd() *cobra.Command { cmd := &cobra.Command{ Use: "lock", @@ -227,7 +227,7 @@ func BurnfromChain33Cmd() *cobra.Command { return cmd } -//BurnAsyncFromChain33Flags ... +// BurnAsyncFromChain33Flags ... func BurnAsyncFromChain33Flags(cmd *cobra.Command) { cmd.Flags().StringP("key", "k", "", "owner private key for chain33") _ = cmd.MarkFlagRequired("key") @@ -295,7 +295,7 @@ func BurnWithIncreaseAsyncFromChain33(cmd *cobra.Command, args []string) { ctx.Run() } -//ImportPrivateKeyCmd SetPwdCmd set password +// ImportPrivateKeyCmd SetPwdCmd set password func ImportPrivateKeyCmd() *cobra.Command { cmd := &cobra.Command{ Use: "import_privatekey", @@ -323,7 +323,7 @@ func importPrivatekey(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowValidatorAddrCmd ... +// ShowValidatorAddrCmd ... func ShowValidatorAddrCmd() *cobra.Command { cmd := &cobra.Command{ Use: "show_validator", @@ -340,7 +340,7 @@ func showValidatorAddr(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowTxsHashCmd ... +// ShowTxsHashCmd ... func ShowTxsHashCmd() *cobra.Command { cmd := &cobra.Command{ Use: "show_txhashes", @@ -402,7 +402,7 @@ func WithdrawFromChain33Cmd() *cobra.Command { return cmd } -//addWithdrawFromChain33CmdFlags ... +// addWithdrawFromChain33CmdFlags ... func addWithdrawFromChain33Flags(cmd *cobra.Command) { cmd.Flags().StringP("key", "k", "", "owner private key for chain33") _ = cmd.MarkFlagRequired("key") diff --git a/plugin/dapp/cross2eth/ebcli/ethereumRelayerCmd.go b/plugin/dapp/cross2eth/ebcli/ethereumRelayerCmd.go index 0d96d7358f..cc5018bef5 100644 --- a/plugin/dapp/cross2eth/ebcli/ethereumRelayerCmd.go +++ b/plugin/dapp/cross2eth/ebcli/ethereumRelayerCmd.go @@ -179,7 +179,7 @@ func getAddressFromPrivateKey(cmd *cobra.Command, args []string) { fmt.Println("addr: ", addr) } -//GenEthPrivateKeyCmd ... +// GenEthPrivateKeyCmd ... func GenEthPrivateKeyCmd() *cobra.Command { cmd := &cobra.Command{ Use: "create_eth_key", @@ -197,7 +197,7 @@ func generateEthereumPrivateKey(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowValidatorsAddrCmd ... +// ShowValidatorsAddrCmd ... func ShowValidatorsAddrCmd() *cobra.Command { cmd := &cobra.Command{ Use: "show_validator", @@ -216,7 +216,7 @@ func showValidatorsAddr(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowChain33TxsHashCmd ... +// ShowChain33TxsHashCmd ... func ShowChain33TxsHashCmd() *cobra.Command { cmd := &cobra.Command{ Use: "show_chain33_tx", @@ -241,7 +241,7 @@ func showChain33Txs(cmd *cobra.Command, args []string) { } } -//IsValidatorActiveCmd ... +// IsValidatorActiveCmd ... func IsValidatorActiveCmd() *cobra.Command { cmd := &cobra.Command{ Use: "active", @@ -252,13 +252,13 @@ func IsValidatorActiveCmd() *cobra.Command { return cmd } -//IsValidatorActiveFlags ... +// IsValidatorActiveFlags ... func IsValidatorActiveFlags(cmd *cobra.Command) { cmd.Flags().StringP("addr", "a", "", "validator address") _ = cmd.MarkFlagRequired("addr") } -//IsValidatorActive ... +// IsValidatorActive ... func IsValidatorActive(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") addr, _ := cmd.Flags().GetString("addr") @@ -269,7 +269,7 @@ func IsValidatorActive(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowOperatorCmd ... +// ShowOperatorCmd ... func ShowOperatorCmd() *cobra.Command { cmd := &cobra.Command{ Use: "operator", @@ -279,7 +279,7 @@ func ShowOperatorCmd() *cobra.Command { return cmd } -//ShowOperator ... +// ShowOperator ... func ShowOperator(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") var res string @@ -336,7 +336,7 @@ func DeployERC20(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowTxReceiptCmd ... +// ShowTxReceiptCmd ... func ShowTxReceiptCmd() *cobra.Command { cmd := &cobra.Command{ Use: "receipt", @@ -347,13 +347,13 @@ func ShowTxReceiptCmd() *cobra.Command { return cmd } -//ShowTxReceiptFlags ... +// ShowTxReceiptFlags ... func ShowTxReceiptFlags(cmd *cobra.Command) { cmd.Flags().StringP("hash", "s", "", "tx hash") _ = cmd.MarkFlagRequired("hash") } -//ShowTxReceipt ... +// ShowTxReceipt ... func ShowTxReceipt(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") ethChainName, _ := cmd.Flags().GetString("eth_chain_name") @@ -369,7 +369,7 @@ func ShowTxReceipt(cmd *cobra.Command, args []string) { ctx.Run() } -//ApproveCmd ... +// ApproveCmd ... func ApproveCmd() *cobra.Command { cmd := &cobra.Command{ Use: "approve", @@ -380,7 +380,7 @@ func ApproveCmd() *cobra.Command { return cmd } -//ApproveAllowanceFlags ... +// ApproveAllowanceFlags ... func ApproveAllowanceFlags(cmd *cobra.Command) { cmd.Flags().StringP("key", "k", "", "owner private key") _ = cmd.MarkFlagRequired("key") @@ -390,7 +390,7 @@ func ApproveAllowanceFlags(cmd *cobra.Command) { _ = cmd.MarkFlagRequired("amount") } -//ApproveAllowance ... +// ApproveAllowance ... func ApproveAllowance(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") key, _ := cmd.Flags().GetString("key") @@ -415,7 +415,7 @@ func ApproveAllowance(cmd *cobra.Command, args []string) { ctx.Run() } -//BurnCmd ... +// BurnCmd ... func BurnCmd() *cobra.Command { cmd := &cobra.Command{ Use: "burn", @@ -426,7 +426,7 @@ func BurnCmd() *cobra.Command { return cmd } -//BurnFlags ... +// BurnFlags ... func BurnFlags(cmd *cobra.Command) { cmd.Flags().StringP("key", "k", "", "owner private key") _ = cmd.MarkFlagRequired("key") @@ -438,7 +438,7 @@ func BurnFlags(cmd *cobra.Command) { _ = cmd.MarkFlagRequired("amount") } -//BurnAsyncCmd ... +// BurnAsyncCmd ... func BurnAsyncCmd() *cobra.Command { cmd := &cobra.Command{ Use: "burn-async", @@ -476,7 +476,7 @@ func Burn(cmd *cobra.Command, args []string) { ctx.Run() } -//BurnAsync ... +// BurnAsync ... func BurnAsync(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") key, _ := cmd.Flags().GetString("key") @@ -501,7 +501,7 @@ func BurnAsync(cmd *cobra.Command, args []string) { ctx.Run() } -//LockSyncCmd ... +// LockSyncCmd ... func LockSyncCmd() *cobra.Command { cmd := &cobra.Command{ Use: "lock", @@ -512,7 +512,7 @@ func LockSyncCmd() *cobra.Command { return cmd } -//LockAsyncCmd ... +// LockAsyncCmd ... func LockAsyncCmd() *cobra.Command { cmd := &cobra.Command{ Use: "lock-async", @@ -523,7 +523,7 @@ func LockAsyncCmd() *cobra.Command { return cmd } -//LockEthErc20AssetFlags ... +// LockEthErc20AssetFlags ... func LockEthErc20AssetFlags(cmd *cobra.Command) { cmd.Flags().StringP("key", "k", "", "owner private key") _ = cmd.MarkFlagRequired("key") @@ -534,7 +534,7 @@ func LockEthErc20AssetFlags(cmd *cobra.Command) { _ = cmd.MarkFlagRequired("receiver") } -//LockEthErc20Asset ... +// LockEthErc20Asset ... func LockEthErc20Asset(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") ethChainName, _ := cmd.Flags().GetString("eth_chain_name") @@ -578,7 +578,7 @@ func LockEthErc20Asset(cmd *cobra.Command, args []string) { } } -//LockEthErc20AssetAsync ... +// LockEthErc20AssetAsync ... func LockEthErc20AssetAsync(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") key, _ := cmd.Flags().GetString("key") @@ -606,7 +606,7 @@ func LockEthErc20AssetAsync(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowBridgeBankAddrCmd ... +// ShowBridgeBankAddrCmd ... func ShowBridgeBankAddrCmd() *cobra.Command { cmd := &cobra.Command{ Use: "bridgeBankAddr", @@ -616,7 +616,7 @@ func ShowBridgeBankAddrCmd() *cobra.Command { return cmd } -//ShowBridgeBankAddr ... +// ShowBridgeBankAddr ... func ShowBridgeBankAddr(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") var res ebTypes.ReplyAddr @@ -624,7 +624,7 @@ func ShowBridgeBankAddr(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowBridgeRegistryAddrCmd ... +// ShowBridgeRegistryAddrCmd ... func ShowBridgeRegistryAddrCmd() *cobra.Command { cmd := &cobra.Command{ Use: "bridgeRegistry", @@ -634,7 +634,7 @@ func ShowBridgeRegistryAddrCmd() *cobra.Command { return cmd } -//ShowBridgeRegistryAddr ... +// ShowBridgeRegistryAddr ... func ShowBridgeRegistryAddr(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") var res ebTypes.ReplyAddr @@ -642,7 +642,7 @@ func ShowBridgeRegistryAddr(cmd *cobra.Command, args []string) { ctx.Run() } -//GetBalanceCmd ... +// GetBalanceCmd ... func ShowBalanceLockedCmd() *cobra.Command { cmd := &cobra.Command{ Use: "showBalanceLocked", @@ -659,7 +659,7 @@ func ShowBalanceLockedFlags(cmd *cobra.Command) { cmd.Flags().StringP("tokenAddr", "t", "", "token address, optional, nil for platform token(Eth)") } -//GetBalance ... +// GetBalance ... func ShowBalanceLocked(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") bridgeBank, _ := cmd.Flags().GetString("bridgeBank") @@ -678,7 +678,7 @@ func ShowBalanceLocked(cmd *cobra.Command, args []string) { ctx.Run() } -//GetBalanceCmd ... +// GetBalanceCmd ... func GetBalanceCmd() *cobra.Command { cmd := &cobra.Command{ Use: "balance", @@ -689,14 +689,14 @@ func GetBalanceCmd() *cobra.Command { return cmd } -//GetBalanceFlags ... +// GetBalanceFlags ... func GetBalanceFlags(cmd *cobra.Command) { cmd.Flags().StringP("owner", "o", "", "owner address") _ = cmd.MarkFlagRequired("owner") cmd.Flags().StringP("tokenAddr", "t", "", "token address, optional, nil for Eth") } -//GetBalance ... +// GetBalance ... func GetBalance(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") ethChainName, _ := cmd.Flags().GetString("eth_chain_name") @@ -713,7 +713,7 @@ func GetBalance(cmd *cobra.Command, args []string) { ctx.Run() } -//TransferTokenCmd ... +// TransferTokenCmd ... func TransferTokenCmd() *cobra.Command { cmd := &cobra.Command{ Use: "token_transfer", @@ -724,7 +724,7 @@ func TransferTokenCmd() *cobra.Command { return cmd } -//TransferTokenFlags ... +// TransferTokenFlags ... func TransferTokenFlags(cmd *cobra.Command) { cmd.Flags().StringP("token", "t", "", "token address") _ = cmd.MarkFlagRequired("token") @@ -736,7 +736,7 @@ func TransferTokenFlags(cmd *cobra.Command) { _ = cmd.MarkFlagRequired("amount") } -//TransferToken ... +// TransferToken ... func TransferToken(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") ethChainName, _ := cmd.Flags().GetString("eth_chain_name") @@ -793,7 +793,7 @@ func GetSelfBalanceCmd() *cobra.Command { return cmd } -//showMultiBalance ... +// showMultiBalance ... func showMultiBalance(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") ethChainName, _ := cmd.Flags().GetString("eth_chain_name") @@ -844,7 +844,6 @@ func ShowEthAddr(cmd *cobra.Command, args []string) { return } fmt.Println(common.ToHex(addr.Hash160[:])) - return } func SetupEthCmd() *cobra.Command { @@ -929,7 +928,7 @@ func SafeTransferEth(cmd *cobra.Command, _ []string) { ctx.Run() } -//ConfigLockedTokenOfflineSaveCmd ... +// ConfigLockedTokenOfflineSaveCmd ... func ConfigLockedTokenOfflineSaveCmd() *cobra.Command { cmd := &cobra.Command{ Use: "set_offline_token", @@ -940,7 +939,7 @@ func ConfigLockedTokenOfflineSaveCmd() *cobra.Command { return cmd } -//ConfigLockedTokenOfflineSaveFlags ... +// ConfigLockedTokenOfflineSaveFlags ... func ConfigLockedTokenOfflineSaveFlags(cmd *cobra.Command) { cmd.Flags().StringP("token", "t", "", "token addr") //_ = cmd.MarkFlagRequired("token") @@ -952,7 +951,7 @@ func ConfigLockedTokenOfflineSaveFlags(cmd *cobra.Command) { //_ = cmd.MarkFlagRequired("percents") } -//ConfigLockedTokenOfflineSave ... +// ConfigLockedTokenOfflineSave ... func ConfigLockedTokenOfflineSave(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") ethChainName, _ := cmd.Flags().GetString("eth_chain_name") diff --git a/plugin/dapp/cross2eth/ebcli/main.go b/plugin/dapp/cross2eth/ebcli/main.go index b1cdfe0557..1c70e3c25f 100644 --- a/plugin/dapp/cross2eth/ebcli/main.go +++ b/plugin/dapp/cross2eth/ebcli/main.go @@ -66,7 +66,7 @@ func testTLS(RPCAddr string) string { return "https://" + RPCAddr[7:] } -//run : +// run : func run(RPCAddr, NodeAddr string) { //test tls is enable RPCAddr = testTLS(RPCAddr) diff --git a/plugin/dapp/cross2eth/ebcli/mulsign4chain33.go b/plugin/dapp/cross2eth/ebcli/mulsign4chain33.go index 10cd8f2df4..33ce09b465 100644 --- a/plugin/dapp/cross2eth/ebcli/mulsign4chain33.go +++ b/plugin/dapp/cross2eth/ebcli/mulsign4chain33.go @@ -53,7 +53,6 @@ func ShowAddr(cmd *cobra.Command, args []string) { return } fmt.Println(common.ToHex(addr.Hash160[:])) - return } func SetupCmd() *cobra.Command { diff --git a/plugin/dapp/cross2eth/ebcli/statics.go b/plugin/dapp/cross2eth/ebcli/statics.go index 7fe3bff285..39e6a6d94e 100644 --- a/plugin/dapp/cross2eth/ebcli/statics.go +++ b/plugin/dapp/cross2eth/ebcli/statics.go @@ -8,7 +8,7 @@ import ( "github.com/spf13/cobra" ) -//StaticsCmd ... +// StaticsCmd ... func StaticsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "statics", @@ -20,7 +20,7 @@ func StaticsCmd() *cobra.Command { return cmd } -//ShowLockStaticsFlags ... +// ShowLockStaticsFlags ... func ShowStaticsFlags(cmd *cobra.Command) { cmd.Flags().StringP("symbol", "s", "", "token symbol(optional)") cmd.Flags().Int32P("from", "f", 0, "source chain, 0=ethereum, and 1=chain33") @@ -32,7 +32,7 @@ func ShowStaticsFlags(cmd *cobra.Command) { cmd.Flags().Int32P("index", "i", 0, "tx index(optional, exclude, default from 0)") } -//ShowLockStatics ... +// ShowLockStatics ... func ShowStatics(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") symbol, _ := cmd.Flags().GetString("symbol") diff --git a/plugin/dapp/cross2eth/ebrelayer/main.go b/plugin/dapp/cross2eth/ebrelayer/main.go index 6bbdef4a7f..51ceefd04d 100644 --- a/plugin/dapp/cross2eth/ebrelayer/main.go +++ b/plugin/dapp/cross2eth/ebrelayer/main.go @@ -162,11 +162,9 @@ func procSig(cancel context.CancelFunc) { sigChannle := make(chan os.Signal, 1) signal.Notify(sigChannle, syscall.SIGTERM) - select { - case <-sigChannle: - cancel() - os.Exit(0) - } + <-sigChannle + cancel() + os.Exit(0) } func convertLogCfg(log *relayerTypes.Log) *chain33Types.Log { @@ -202,12 +200,12 @@ func initCfg(path string) *relayerTypes.RelayerConfig { return &cfg } -//IsIPWhiteListEmpty ... +// IsIPWhiteListEmpty ... func IsIPWhiteListEmpty() bool { return len(IPWhiteListMap) == 0 } -//IsInIPWhitelist 判断ipAddr是否在ip地址白名单中 +// IsInIPWhitelist 判断ipAddr是否在ip地址白名单中 func IsInIPWhitelist(ipAddrPort string) bool { ipAddr, _, err := net.SplitHostPort(ipAddrPort) if err != nil { @@ -223,12 +221,12 @@ func IsInIPWhitelist(ipAddrPort string) bool { return false } -//RPCServer ... +// RPCServer ... type RPCServer struct { *rpc.Server } -//ServeHTTP ... +// ServeHTTP ... func (r *RPCServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { mainlog.Info("ServeHTTP", "request address", req.RemoteAddr) if !IsIPWhiteListEmpty() { @@ -241,24 +239,24 @@ func (r *RPCServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { r.Server.ServeHTTP(w, req) } -//HandleHTTP ... +// HandleHTTP ... func (r *RPCServer) HandleHTTP(rpcPath, debugPath string) { http.Handle(rpcPath, r) } -//HTTPConn ... +// HTTPConn ... type HTTPConn struct { in io.Reader out io.Writer } -//Read ... +// Read ... func (c *HTTPConn) Read(p []byte) (n int, err error) { return c.in.Read(p) } -//Write ... +// Write ... func (c *HTTPConn) Write(d []byte) (n int, err error) { return c.out.Write(d) } -//Close ... +// Close ... func (c *HTTPConn) Close() error { return nil } func startRPCServer(address string, api interface{}) { diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/chain33.go b/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/chain33.go index 4781582af0..e960e287af 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/chain33.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/chain33.go @@ -33,7 +33,7 @@ import ( var relayerLog = log.New("module", "chain33_relayer") -//Relayer4Chain33 ... +// Relayer4Chain33 ... type Relayer4Chain33 struct { syncEvmTxLogs *syncTx.EVMTxLogs rpcLaddr string //用户向指定的blockchain节点进行rpc调用 @@ -633,7 +633,7 @@ func (chain33Relayer *Relayer4Chain33) LockBTYAssetAsync(ownerPrivateKey, ethere return lockAsync(ownerPrivateKey, ethereumReceiver, bn.Int64(), chain33Relayer.bridgeBankAddr, chain33Relayer.chainName, chain33Relayer.rpcLaddr) } -//ShowBridgeRegistryAddr ... +// ShowBridgeRegistryAddr ... func (chain33Relayer *Relayer4Chain33) ShowBridgeRegistryAddr() (string, error) { if "" == chain33Relayer.bridgeRegistryAddr { return "", errors.New("the relayer is not started yet") @@ -719,7 +719,7 @@ func (chain33Relayer *Relayer4Chain33) checkTxRelay2Ethereum() { } } -//用于chain33的事件信息被中继之后的ack信息,重置标志位 +// 用于chain33的事件信息被中继之后的ack信息,重置标志位 func (chain33Relayer *Relayer4Chain33) procTxRelayAck(ack *ebTypes.TxRelayAck) { //reset with another key to exclude from the check list to resend the same message if err := chain33Relayer.resetKeyChain33TxRelayedAlready(ack.TxHash); nil != err { diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/store.go b/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/store.go index c86efc5c41..e6da9205e4 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/store.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/store.go @@ -11,7 +11,7 @@ import ( "github.com/33cn/plugin/plugin/dapp/cross2eth/ebrelayer/utils" ) -//key ... +// key ... var ( lastSyncHeightPrefix = []byte("chain33-lastSyncHeight:") eth2Chain33BurnLockTxStaticsPrefix = "chain33-eth2chain33BurnLockStatics" @@ -49,7 +49,7 @@ func calcRelayFromEthStaticsKey(txindex int64, claimType int32) []byte { return []byte(fmt.Sprintf("%s-%d-%012d", eth2Chain33BurnLockTxStaticsPrefix, claimType, txindex)) } -//未完成,处在pending状态 +// 未完成,处在pending状态 func calcRelayFromEthStaticsList(claimType int32) []byte { return []byte(fmt.Sprintf("%s-%d-", eth2Chain33BurnLockTxStaticsPrefix, claimType)) } @@ -194,7 +194,7 @@ func (chain33Relayer *Relayer4Chain33) getChain33UpdateTxIndex(claimType events. return txIndexWrapper.Data } -//获取上次同步到app的高度 +// 获取上次同步到app的高度 func (chain33Relayer *Relayer4Chain33) loadLastSyncHeight() int64 { height, err := utils.LoadInt64FromDB(lastSyncHeightPrefix, chain33Relayer.db) if nil != err && err != chain33Types.ErrHeightNotExist { @@ -321,7 +321,7 @@ func (chain33Relayer *Relayer4Chain33) restoreSymbol2chainName() map[string]stri return symbol2EthChain.Symbol2Name } -//判断是否已经被处理,如果能够在数据库中找到该笔交易,则认为已经被处理 +// 判断是否已经被处理,如果能够在数据库中找到该笔交易,则认为已经被处理 func (chain33Relayer *Relayer4Chain33) checkTxProcessed(txhash string) bool { key1 := chain33TxIsRelayedUnconfirmKey(txhash) data, err := chain33Relayer.db.Get(key1) diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/transceiver/sync/proc.go b/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/transceiver/sync/proc.go index 32dbd5150d..afbc4d79c0 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/transceiver/sync/proc.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/transceiver/sync/proc.go @@ -42,7 +42,7 @@ func pushTxReceipts(evmTxLogsInBlks *types.EVMTxLogsInBlks) error { return err } -//EVMTxLogs ... +// EVMTxLogs ... type EVMTxLogs struct { db dbm.DB seqNum int64 //当前同步的序列号 @@ -50,7 +50,7 @@ type EVMTxLogs struct { quit chan struct{} } -//NewSyncTxReceipts ... +// NewSyncTxReceipts ... func NewSyncTxReceipts(db dbm.DB) *EVMTxLogs { sync := &EVMTxLogs{ db: db, @@ -63,7 +63,7 @@ func NewSyncTxReceipts(db dbm.DB) *EVMTxLogs { return sync } -//此处添加一个高度为0的空块,只是为了查找下一个比较方便,并不需要使用其信息 +// 此处添加一个高度为0的空块,只是为了查找下一个比较方便,并不需要使用其信息 func (syncTx *EVMTxLogs) initSyncReceiptDataBase() { txLogs0, _ := syncTx.GetTxLogs(0) if nil != txLogs0 { @@ -75,7 +75,7 @@ func (syncTx *EVMTxLogs) initSyncReceiptDataBase() { syncTx.setTxLogsPerBlock(logsPerBlock) } -//Stop ... +// Stop ... func (syncTx *EVMTxLogs) Stop() { close(syncTx.quit) } @@ -141,7 +141,7 @@ func (syncTx *EVMTxLogs) loadBlockLastSequence() (int64, error) { return utils.LoadInt64FromDB(lastSequences, syncTx.db) } -//LoadLastBlockHeight ... +// LoadLastBlockHeight ... func (syncTx *EVMTxLogs) LoadLastBlockHeight() (int64, error) { return utils.LoadInt64FromDB(syncLastHeight, syncTx.db) } @@ -173,7 +173,7 @@ func (syncTx *EVMTxLogs) setTxLogsPerBlock(txLogs *types.EVMTxLogPerBlk) { } } -//GetTxReceipts ... +// GetTxReceipts ... func (syncTx *EVMTxLogs) GetTxLogs(height int64) (*types.TxReceipts4SubscribePerBlk, error) { key := evmTxLogKey4Height(height) value, err := syncTx.db.Get(key) @@ -188,7 +188,7 @@ func (syncTx *EVMTxLogs) GetTxLogs(height int64) (*types.TxReceipts4SubscribePer return detail, nil } -//GetNextValidTxReceipts ... +// GetNextValidTxReceipts ... func (syncTx *EVMTxLogs) GetNextValidEvmTxLogs(height int64) (*types.EVMTxLogPerBlk, error) { key := evmTxLogKey4Height(height) helper := dbm.NewListHelper(syncTx.db) diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/transceiver/sync/pubilc_sync.go b/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/transceiver/sync/pubilc_sync.go index 73ecc94427..fcf119502e 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/transceiver/sync/pubilc_sync.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/transceiver/sync/pubilc_sync.go @@ -1,6 +1,6 @@ package sync -//HandleRequest ... +// HandleRequest ... func HandleRequest(body []byte) error { return handleRequest(body) } diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/transceiver/sync/sync_tx_receipts.go b/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/transceiver/sync/sync_tx_receipts.go index de67ea91ef..84b14a6bd4 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/transceiver/sync/sync_tx_receipts.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/transceiver/sync/sync_tx_receipts.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//Package sync ... +// Package sync ... package sync import ( @@ -31,7 +31,7 @@ var ( minDuration2KeepAlive = time.Duration(180*1000) * time.Millisecond //三分钟 ) -//StartSyncTxReceipt ... +// StartSyncTxReceipt ... func StartSyncEvmTxLogs(cfg *relayerTypes.SyncTxReceiptConfig, db dbm.DB) *EVMTxLogs { log.Debug("StartSyncEvmTxLogs, load config", "para:", cfg) log.Debug("EVMTxLogs started ") @@ -57,14 +57,11 @@ func keepSubscriptionAlive(cfg *relayerTypes.SyncTxReceiptConfig) { timer2KeepAlive = time.NewTicker(duration2KeepAlive) log.Debug("keepSubscriptionAlive", "duration2KeepAlive", duration2KeepAlive) - for { - select { - case <-timer2KeepAlive.C: - bindOrResumePush(cfg) - now := time.Now() - _, month, day := now.Date() - log.Debug("keepSubscriptionAlive", "time stamp month", month, "day", day, "hour", now.Hour(), "minute", now.Minute()) - } + for range timer2KeepAlive.C { + bindOrResumePush(cfg) + now := time.Now() + _, month, day := now.Date() + log.Debug("keepSubscriptionAlive", "time stamp month", month, "day", day, "hour", now.Hour(), "minute", now.Minute()) } } @@ -148,9 +145,9 @@ func checkClient(addr string, expectClient string) bool { return addr == expectClient } -//向chain33节点的注册推送交易回执,AddSubscribeTxReceipt具有2种功能: -//首次注册功能,如果没有进行过注册,则进行首次注册 -//如果已经注册,则继续推送 +// 向chain33节点的注册推送交易回执,AddSubscribeTxReceipt具有2种功能: +// 首次注册功能,如果没有进行过注册,则进行首次注册 +// 如果已经注册,则继续推送 func bindOrResumePush(cfg *relayerTypes.SyncTxReceiptConfig) { contract := make(map[string]bool) for _, name := range cfg.Contracts { diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/tx.go b/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/tx.go index b019bd8fa7..e746c9377a 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/tx.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/chain33/tx.go @@ -191,8 +191,7 @@ func deploySingleContract(code []byte, abi, constructorPara, contractName, paraC exector := paraChainName + "evm" to := address.ExecAddress(exector) - var action evmtypes.EVMContractAction - action = evmtypes.EVMContractAction{Amount: 0, Code: code, GasLimit: 0, GasPrice: 0, Note: note, Alias: contractName, ContractAddr: to} + action := evmtypes.EVMContractAction{Amount: 0, Code: code, GasLimit: 0, GasPrice: 0, Note: note, Alias: contractName, ContractAddr: to} if constructorPara != "" { packData, err := evmAbi.PackContructorPara(constructorPara, abi) if err != nil { @@ -418,7 +417,7 @@ func setupMultiSign(ownerPrivateKeyStr, contractAddr, chainName, rpcURL string, // address payable paymentReceiver //) parameter := "setup([" - parameter += fmt.Sprintf("%s", owners[0]) + parameter += owners[0] for _, owner := range owners[1:] { parameter += fmt.Sprintf(",%s", owner) } @@ -549,7 +548,7 @@ func safeTransfer(ownerPrivateKeyStr, mulSign, chainName, rpcURL, receiver, toke } func recoverContractAddrFromRegistry(bridgeRegistry, rpcLaddr string) (oracle, bridgeBank string) { - parameter := fmt.Sprint("oracle()") + parameter := "oracle()" result := query(bridgeRegistry, parameter, bridgeRegistry, rpcLaddr, generated.BridgeRegistryABI) if nil == result { @@ -557,7 +556,7 @@ func recoverContractAddrFromRegistry(bridgeRegistry, rpcLaddr string) (oracle, b } oracle = result.(string) - parameter = fmt.Sprint("bridgeBank()") + parameter = "bridgeBank()" result = query(bridgeRegistry, parameter, bridgeRegistry, rpcLaddr, generated.BridgeRegistryABI) if nil == result { return "", "" @@ -587,7 +586,7 @@ func getBridgeToken2address(bridgeBank, symbol, rpcLaddr string) string { } func getMulSignNonce(mulsign, rpcLaddr string) int64 { - parameter := fmt.Sprintf("nonce()") + parameter := "nonce()" result := query(mulsign, parameter, mulsign, rpcLaddr, generated.GnosisSafeABI) if nil == result { diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/account.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/account.go index 03a5ae51cf..83b420a6ff 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/account.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/account.go @@ -21,7 +21,7 @@ var ( start = int(1) ) -//Key ... +// Key ... type Key struct { ID uuid.UUID // Version 4 "random" for unique id not derived from key data // to simplify lookups we also store the address @@ -31,7 +31,7 @@ type Key struct { PrivateKey *ecdsa.PrivateKey } -//NewAccount ... +// NewAccount ... func NewAccount() (privateKeystr, addr string, err error) { _, privateKeystr, addr, err = newKeyAndStore(crand.Reader) if err != nil { @@ -40,7 +40,7 @@ func NewAccount() (privateKeystr, addr string, err error) { return } -//GetAccount ... +// GetAccount ... func (ethRelayer *Relayer4Ethereum) GetAccount(passphrase string) (privateKey, addr string, err error) { accountInfo, err := ethRelayer.db.Get(ethAccountKey) if nil != err { @@ -56,7 +56,7 @@ func (ethRelayer *Relayer4Ethereum) GetAccount(passphrase string) (privateKey, a return } -//GetValidatorAddr ... +// GetValidatorAddr ... func (ethRelayer *Relayer4Ethereum) GetValidatorAddr() (validators x2ethTypes.ValidatorAddr4EthRelayer, err error) { var chain33AccountAddr string accountInfo, err := ethRelayer.db.Get(ethAccountKey) @@ -104,7 +104,7 @@ func (ethRelayer *Relayer4Ethereum) ImportPrivateKey(passphrase, privateKeyStr s return } -//RestorePrivateKeys ... +// RestorePrivateKeys ... func (ethRelayer *Relayer4Ethereum) RestorePrivateKeys(passphrase string) error { accountInfo, err := ethRelayer.db.Get(ethAccountKey) if nil != err { @@ -131,7 +131,7 @@ func (ethRelayer *Relayer4Ethereum) RestorePrivateKeys(passphrase string) error return nil } -//StoreAccountWithNewPassphase ... +// StoreAccountWithNewPassphase ... func (ethRelayer *Relayer4Ethereum) StoreAccountWithNewPassphase(newPassphrase, oldPassphrase string) error { accountInfo, err := ethRelayer.db.Get(ethAccountKey) if nil != err { @@ -149,7 +149,7 @@ func (ethRelayer *Relayer4Ethereum) StoreAccountWithNewPassphase(newPassphrase, return ethRelayer.db.SetSync(ethAccountKey, encodedInfo) } -//checksum: first four bytes of double-SHA256. +// checksum: first four bytes of double-SHA256. func checksum(input []byte) (cksum [4]byte) { h := sha256.New() _, err := h.Write(input) diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethereum.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethereum.go index 97803d9734..75ba1139be 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethereum.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethereum.go @@ -348,7 +348,7 @@ func (ethRelayer *Relayer4Ethereum) ShowTxReceipt(hash string) (*types.Receipt, func (ethRelayer *Relayer4Ethereum) getClientSpecs() { var err error bSendEmail := false - for true { + for { ethRelayer.clientSpecs, ethRelayer.clientChainID, err = ethtxs.SetupEthClients(ðRelayer.providerHttp, ethRelayer.bridgeRegistryAddr) if err != nil { if !bSendEmail { @@ -371,7 +371,7 @@ func (ethRelayer *Relayer4Ethereum) getClientSpecs() { func (ethRelayer *Relayer4Ethereum) getClientWss() { var err error bSendEmail := false - for true { + for { ethRelayer.clientWss, _, err = ethtxs.SetupEthClient(ðRelayer.provider) if err != nil { if !bSendEmail { @@ -480,7 +480,6 @@ func (ethRelayer *Relayer4Ethereum) handleChain33Msg(chain33Msg *events.Chain33M } ethRelayer.handleLogLockBurn(chain33Msg) - return } func (ethRelayer *Relayer4Ethereum) checkPermissionWithinOneDay(withdrawTx *ebTypes.WithdrawTx) (*big.Int, error) { @@ -517,7 +516,7 @@ func (ethRelayer *Relayer4Ethereum) SendRemind(url, postData string) { return } result := js.Get("result").MustBool() - if result == false { + if !result { reErr := js.Get("error").MustString() relayerLog.Error("SendToServer", "send error:", reErr) return @@ -697,7 +696,6 @@ func (ethRelayer *Relayer4Ethereum) handleLogWithdraw(chain33Msg *events.Chain33 withdrawTx.StatusDescription = ethtxs.WDPending.String() withdrawTx.TxHashOnEthereum = ethTxhash - return } func (ethRelayer *Relayer4Ethereum) NewTransferSignTx(toAddr common.Address, intputData []byte, value *big.Int, fromChain bool) (*types.Transaction, error) { @@ -737,7 +735,7 @@ func (ethRelayer *Relayer4Ethereum) checkBalanceEnough(addr common.Address, amou var ok bool balance, ok = big.NewInt(1).SetString(common.Bytes2Hex(result), 16) if !ok { - return errors.New(fmt.Sprintf("token balance err:%v", common.Bytes2Hex(result))) + return fmt.Errorf("token balance err:%v", common.Bytes2Hex(result)) } } @@ -1014,7 +1012,6 @@ func (ethRelayer *Relayer4Ethereum) getAvailableClient() { break } } - return } func (ethRelayer *Relayer4Ethereum) getCurrentHeight() (uint64, error) { @@ -1482,7 +1479,7 @@ func (ethRelayer *Relayer4Ethereum) subscribeEvent() { // We will check logs for new events logs := make(chan types.Log, 10) - for true { + for { // Filter by contract and event, write results to logs sub, err := ethRelayer.clientWss.SubscribeFilterLogs(context.Background(), query, logs) if err != nil { @@ -1828,7 +1825,7 @@ func (ethRelayer *Relayer4Ethereum) sendEthereumTx(signedTx *types.Transaction) } } - if bSuccess == false { + if !bSuccess { return err } else { return nil @@ -1861,7 +1858,7 @@ func (ethRelayer *Relayer4Ethereum) regainClient(isSendEmail *bool) { relayerLog.Error("regainClient", "SetupEthClient err", err) } - if len(ethRelayer.clientSpecs) == 0 && *isSendEmail == false { + if len(ethRelayer.clientSpecs) == 0 && !*isSendEmail { // 节点都不可用 发送邮件 ethRelayer.remindSetupEthClientError() *isSendEmail = true diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/abi.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/abi.go index 3a68d63a09..6206652701 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/abi.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/abi.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" ) -//const +// const const ( BridgeBankABI = "BridgeBankABI" Chain33BankABI = "Chain33BankABI" @@ -16,7 +16,7 @@ const ( OracleABI = "OracleABI" ) -//LoadABI ... +// LoadABI ... func LoadABI(contractName string) abi.ABI { var abiJSON string switch contractName { diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/auxiliary.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/auxiliary.go index 510b2f8bff..6431a4b27c 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/auxiliary.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/auxiliary.go @@ -19,7 +19,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" ) -//NewProphecyClaimPara ... +// NewProphecyClaimPara ... type NewProphecyClaimPara struct { ClaimType uint8 Chain33Sender []byte @@ -30,7 +30,7 @@ type NewProphecyClaimPara struct { Txhash []byte } -//Burn ... +// Burn ... func Burn(ownerPrivateKeyStr, tokenAddrstr, chain33Receiver string, bridgeBank common.Address, amount *big.Int, bridgeBankIns *generated.BridgeBank, client ethinterface.EthClientSpec, addr2TxNonce map[common.Address]*NonceMutex, providerHttp string) (string, error) { ownerPrivateKey, err := crypto.ToECDSA(common.FromHex(ownerPrivateKeyStr)) @@ -96,7 +96,7 @@ func Burn(ownerPrivateKeyStr, tokenAddrstr, chain33Receiver string, bridgeBank c return tx.Hash().String(), nil } -//BurnAsync ... +// BurnAsync ... func BurnAsync(ownerPrivateKeyStr, tokenAddrstr, chain33Receiver string, amount *big.Int, bridgeBankIns *generated.BridgeBank, client ethinterface.EthClientSpec, addr2TxNonce map[common.Address]*NonceMutex) (string, error) { ownerPrivateKey, err := crypto.ToECDSA(common.FromHex(ownerPrivateKeyStr)) @@ -134,7 +134,7 @@ func BurnAsync(ownerPrivateKeyStr, tokenAddrstr, chain33Receiver string, amount return tx.Hash().String(), nil } -//TransferToken ... +// TransferToken ... func TransferToken(tokenAddr, fromPrivateKeyStr, toAddr string, amount *big.Int, client ethinterface.EthClientSpec, addr2TxNonce map[common.Address]*NonceMutex, providerHttp string) (string, error) { tokenInstance, err := generated.NewBridgeToken(common.HexToAddress(tokenAddr), client) if nil != err { @@ -238,7 +238,7 @@ func TransferEth(fromPrivateKeyStr, toAddr string, amount *big.Int, client ethin return signedTx.Hash().String(), nil } -//LockEthErc20Asset ... +// LockEthErc20Asset ... func LockEthErc20Asset(ownerPrivateKeyStr, tokenAddrStr, chain33Receiver string, amount *big.Int, client ethinterface.EthClientSpec, bridgeBank *generated.BridgeBank, bridgeBankAddr common.Address, addr2TxNonce map[common.Address]*NonceMutex, providerHttp string) (string, error) { var prepareDone bool txslog.Info("LockEthErc20Asset", "ownerPrivateKeyStr", ownerPrivateKeyStr, "tokenAddrStr", tokenAddrStr, "chain33Receiver", chain33Receiver, "amount", amount.String()) @@ -317,7 +317,7 @@ func LockEthErc20Asset(ownerPrivateKeyStr, tokenAddrStr, chain33Receiver string, return tx.Hash().String(), nil } -//LockEthErc20AssetAsync ... +// LockEthErc20AssetAsync ... func LockEthErc20AssetAsync(ownerPrivateKeyStr, tokenAddrStr, chain33Receiver string, amount *big.Int, client ethinterface.EthClientSpec, bridgeBank *generated.BridgeBank, addr2TxNonce map[common.Address]*NonceMutex) (string, error) { txslog.Info("LockEthErc20AssetAsync", "ownerPrivateKeyStr", ownerPrivateKeyStr, "tokenAddrStr", tokenAddrStr, "chain33Receiver", chain33Receiver, "amount", amount.String()) ownerPrivateKey, err := crypto.ToECDSA(common.FromHex(ownerPrivateKeyStr)) diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/deploy.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/deploy.go index 702cbaf2d4..6b1c6c6bc3 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/deploy.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/deploy.go @@ -13,13 +13,13 @@ var ( deployLog = log15.New("contract deployer", "deployer") ) -//DeployResult ... +// DeployResult ... type DeployResult struct { Address common.Address TxHash string } -//X2EthContracts ... +// X2EthContracts ... type X2EthContracts struct { BridgeRegistry *generated.BridgeRegistry BridgeBank *generated.BridgeBank @@ -28,7 +28,7 @@ type X2EthContracts struct { Oracle *generated.Oracle } -//X2EthDeployResult ... +// X2EthDeployResult ... type X2EthDeployInfo struct { BridgeRegistry *DeployResult BridgeBank *DeployResult @@ -37,7 +37,7 @@ type X2EthDeployInfo struct { Oracle *DeployResult } -//DeployPara ... +// DeployPara ... type DeployPara struct { DeployPrivateKey *ecdsa.PrivateKey Deployer common.Address @@ -47,7 +47,7 @@ type DeployPara struct { InitPowers []*big.Int } -//OperatorInfo ... +// OperatorInfo ... type OperatorInfo struct { PrivateKey *ecdsa.PrivateKey Address common.Address diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/ethtxs_test.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/ethtxs_test.go index ee1e462c67..2fd77c35a3 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/ethtxs_test.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/ethtxs_test.go @@ -182,7 +182,7 @@ func PrepareTestEnvironment(deployerPrivateKey string, ethValidatorAddrKeys []st return sim, para } -//DeployValset : 部署Valset +// DeployValset : 部署Valset func DeployValset(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer common.Address, operator common.Address, initValidators []common.Address, initPowers []*big.Int) (*generated.Valset, *DeployResult, error) { auth, err := PrepareAuth(client, privateKey, deployer) if nil != err { @@ -203,7 +203,7 @@ func DeployValset(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKe return valset, deployResult, nil } -//DeployChain33Bridge : 部署Chain33Bridge +// DeployChain33Bridge : 部署Chain33Bridge func DeployChain33Bridge(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer common.Address, operator, valset common.Address) (*generated.Chain33Bridge, *DeployResult, error) { auth, err := PrepareAuth(client, privateKey, deployer) if nil != err { @@ -223,7 +223,7 @@ func DeployChain33Bridge(client ethinterface.EthClientSpec, privateKey *ecdsa.Pr return chain33Bridge, deployResult, nil } -//DeployOracle : 部署Oracle +// DeployOracle : 部署Oracle func DeployOracle(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer, operator, valset, chain33Bridge common.Address) (*generated.Oracle, *DeployResult, error) { auth, err := PrepareAuth(client, privateKey, deployer) if nil != err { @@ -243,7 +243,7 @@ func DeployOracle(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKe return oracle, deployResult, nil } -//DeployBridgeBank : 部署BridgeBank +// DeployBridgeBank : 部署BridgeBank func DeployBridgeBank(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer, operator, oracle, chain33Bridge common.Address) (*generated.BridgeBank, *DeployResult, error) { auth, err := PrepareAuth(client, privateKey, deployer) if nil != err { @@ -263,7 +263,7 @@ func DeployBridgeBank(client ethinterface.EthClientSpec, privateKey *ecdsa.Priva return bridgeBank, deployResult, nil } -//DeployBridgeRegistry : 部署BridgeRegistry +// DeployBridgeRegistry : 部署BridgeRegistry func DeployBridgeRegistry(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer, chain33BridgeAddr, bridgeBankAddr, oracleAddr, valsetAddr common.Address) (*generated.BridgeRegistry, *DeployResult, error) { auth, err := PrepareAuth(client, privateKey, deployer) if nil != err { @@ -283,7 +283,7 @@ func DeployBridgeRegistry(client ethinterface.EthClientSpec, privateKey *ecdsa.P return bridgeRegistry, deployResult, nil } -//DeployAndInit ... +// DeployAndInit ... func DeployAndInit(client ethinterface.EthClientSpec, para *DeployPara) (*X2EthContracts, *X2EthDeployInfo, error) { x2EthContracts := &X2EthContracts{} deployInfo := &X2EthDeployInfo{} diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/parser.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/parser.go index 861bce87eb..83c4b4ceaf 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/parser.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/parser.go @@ -43,7 +43,7 @@ func LogLockToEthBridgeClaim(event *events.LockEvent, ethereumChainID int64, bri return witnessClaim, nil } -//LogBurnToEthBridgeClaim ... +// LogBurnToEthBridgeClaim ... func LogBurnToEthBridgeClaim(event *events.BurnEvent, ethereumChainID int64, bridgeBrankAddr, ethTxHash string, decimal int64) (*ebrelayerTypes.EthBridgeClaim, error) { recipient := event.Chain33Receiver if 0 == len(recipient) { diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/queryFromEth.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/queryFromEth.go index 1ea83203e6..17f98b977f 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/queryFromEth.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/queryFromEth.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum/common" ) -//GetOperator ... +// GetOperator ... func GetOperator(client ethinterface.EthClientSpec, sender, bridgeBank common.Address) (common.Address, error) { header, err := client.HeaderByNumber(context.Background(), nil) if err != nil { @@ -37,7 +37,7 @@ func GetOperator(client ethinterface.EthClientSpec, sender, bridgeBank common.Ad return bridgeBankInstance.Operator(&auth) } -//IsActiveValidator ... +// IsActiveValidator ... func IsActiveValidator(validator common.Address, valset *generated.Valset) (bool, error) { opts := &bind.CallOpts{ Pending: true, @@ -55,7 +55,7 @@ func IsActiveValidator(validator common.Address, valset *generated.Valset) (bool return isActiveValidator, nil } -//IsProphecyPending ... +// IsProphecyPending ... func IsProphecyPending(claimID [32]byte, validator common.Address, chain33Bridge *generated.Chain33Bridge) (bool, error) { opts := &bind.CallOpts{ Pending: true, @@ -72,7 +72,7 @@ func IsProphecyPending(claimID [32]byte, validator common.Address, chain33Bridge return active, nil } -//GetBalance ... +// GetBalance ... func GetBalance(client ethinterface.EthClientSpec, tokenAddr, owner string) (string, error) { //查询ERC20余额 if tokenAddr != "" { @@ -103,7 +103,7 @@ func GetBalance(client ethinterface.EthClientSpec, tokenAddr, owner string) (str return balance.String(), nil } -//GetLockedFunds ... +// GetLockedFunds ... func GetLockedFunds(bridgeBank *generated.BridgeBank, tokenAddrStr string) (string, error) { var tokenAddr common.Address if tokenAddrStr != "" { @@ -121,7 +121,7 @@ func GetLockedFunds(bridgeBank *generated.BridgeBank, tokenAddrStr string) (stri return balance.String(), nil } -//GetDepositFunds ... +// GetDepositFunds ... func GetDepositFunds(client bind.ContractBackend, tokenAddrStr string) (string, error) { if tokenAddrStr == "" { return "", errors.New("nil token address") @@ -145,7 +145,7 @@ func GetDepositFunds(client bind.ContractBackend, tokenAddrStr string) (string, return supply.String(), nil } -//GetToken2address ... +// GetToken2address ... func GetToken2address(bridgeBank *generated.BridgeBank, tokenSymbol string) (string, error) { opts := &bind.CallOpts{ Pending: true, @@ -160,7 +160,7 @@ func GetToken2address(bridgeBank *generated.BridgeBank, tokenSymbol string) (str return tokenAddr.String(), nil } -//GetLockedTokenAddress ... +// GetLockedTokenAddress ... func GetLockedTokenAddress(bridgeBank *generated.BridgeBank, tokenSymbol string) (string, error) { opts := &bind.CallOpts{ Pending: true, diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/recover.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/recover.go index 16097f8c63..8ad75cd563 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/recover.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/recover.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/common" ) -//RecoverContractHandler ... +// RecoverContractHandler ... func RecoverContractHandler(client ethinterface.EthClientSpec, sender, registry common.Address) (*X2EthContracts, *X2EthDeployInfo, error) { bridgeBankAddr, err := GetAddressFromBridgeRegistry(client, sender, registry, BridgeBank) if nil != err { @@ -66,7 +66,7 @@ func RecoverContractHandler(client ethinterface.EthClientSpec, sender, registry return x2EthContracts, x2EthDeployInfo, nil } -//RecoverOracleInstance ... +// RecoverOracleInstance ... func RecoverOracleInstance(client ethinterface.EthClientSpec, sender, registry common.Address) (*generated.Oracle, error) { oracleAddr, err := GetAddressFromBridgeRegistry(client, sender, registry, Oracle) if nil != err { diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/relayToEthereum.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/relayToEthereum.go index 06478d4987..316b5a3de6 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/relayToEthereum.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/relayToEthereum.go @@ -86,7 +86,7 @@ func RelayOracleClaimToEthereum(burnOrLockParameter *BurnOrLockParameter) (strin txslog.Info("RelayProphecyClaimToEthereum", "sender", sender.String(), "nonce", auth.Nonce, "claim.chain33TxHash", chain33Common.ToHex(claim.Chain33TxHash), "claimID", claimID.String()) var txhash string - for true { + for { tx, err := ethClientWithUrl.OracleInstance.NewOracleClaim(auth, uint8(claim.ClaimType), claim.Chain33Sender, claim.EthereumReceiver, tokenOnEth, claim.Symbol, claim.Amount, claimID, signature) // 如果不是金额不够的错误, 直接 return 报错退出 if nil != err { diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/types.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/types.go index 3983699b0c..515ed2ab0e 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/types.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/types.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" ) -//const ... +// const ... const ( EthNullAddr = "0x0000000000000000000000000000000000000000" ) diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/utils.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/utils.go index e38541e6d5..d7d474894f 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/utils.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/ethtxs/utils.go @@ -17,7 +17,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" ) -//EthTxStatus ... +// EthTxStatus ... type EthTxStatus int32 type NonceMutex struct { @@ -31,12 +31,12 @@ var ( ErrNodeNetwork = errors.New("ErrNodeNetwork") ) -//String ... +// String ... func (ethTxStatus EthTxStatus) String() string { return [...]string{"Fail", "Success", "Pending"}[ethTxStatus] } -//const +// const const ( PendingDuration4TxExeuction = 300 EthTxPending = EthTxStatus(2) @@ -44,7 +44,7 @@ const ( // fromChain 是否从链上获取 func getNonce4MultiEth(sender common.Address, client ethinterface.EthClientSpec, addr2TxNonce map[common.Address]*NonceMutex, fromChain bool) (*big.Int, error) { - if fromChain == false { + if !fromChain { if nonceMutex, exist := addr2TxNonce[sender]; exist { nonceMutex.RWLock.Lock() defer nonceMutex.RWLock.Unlock() @@ -113,7 +113,7 @@ func revokeNonce(sender common.Address) (*big.Int, error) { return nil, errors.New("address doesn't exist tx") } -//PrepareAuth ... +// PrepareAuth ... func PrepareAuth(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, transactor common.Address) (*bind.TransactOpts, error) { if nil == privateKey || nil == client { txslog.Error("PrepareAuth", "nil input parameter", "client", client, "privateKey", privateKey) @@ -262,7 +262,7 @@ func waitEthTxFinished(client ethinterface.EthClientSpec, txhash common.Hash, tx } } -//GetEthTxStatus ... +// GetEthTxStatus ... func GetEthTxStatus(client ethinterface.EthClientSpec, txhash common.Hash) string { receipt, err := client.TransactionReceipt(context.Background(), txhash) if nil != err { diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/store.go b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/store.go index 926c182736..03620f9f5a 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/store.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/ethereum/store.go @@ -290,7 +290,7 @@ func (ethRelayer *Relayer4Ethereum) getLastBridgeBankProcessedHeight() ebTypes.E return logIndex } -//构建一个引导查询使用的bridgeBankTx +// 构建一个引导查询使用的bridgeBankTx func (ethRelayer *Relayer4Ethereum) initBridgeBankTx() { log, _ := ethRelayer.getEthTxEvent(0, 0) if nil != log { @@ -659,7 +659,7 @@ func (ethRelayer *Relayer4Ethereum) getAllTxsUnconfirm() (txInfos []*ebTypes.TxR return } -//判断是否已经被处理,如果能够在数据库中找到该笔交易,则认为已经被处理 +// 判断是否已经被处理,如果能够在数据库中找到该笔交易,则认为已经被处理 func (ethRelayer *Relayer4Ethereum) checkTxProcessed(txhash string) bool { key1 := ethTxIsRelayedUnconfirmKey(ethRelayer.name, txhash) data, err := ethRelayer.db.Get(key1) diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/events/ethereumEvent.go b/plugin/dapp/cross2eth/ebrelayer/relayer/events/ethereumEvent.go index b227cb9f4d..09cd296479 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/events/ethereumEvent.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/events/ethereumEvent.go @@ -67,7 +67,7 @@ type NewProphecyClaimEvent struct { Amount *big.Int } -//LogNewBridgeToken ... +// LogNewBridgeToken ... type LogNewBridgeToken struct { Token common.Address Symbol string @@ -101,7 +101,7 @@ func UnpackLogLock(contractAbi abi.ABI, eventName string, eventData []byte) (loc return event, nil } -//UnpackLogBurn ... +// UnpackLogBurn ... func UnpackLogBurn(contractAbi abi.ABI, eventName string, eventData []byte) (burnEvent *BurnEvent, err error) { event := &BurnEvent{} // Parse the event's attributes as Ethereum network variables diff --git a/plugin/dapp/cross2eth/ebrelayer/relayer/manager.go b/plugin/dapp/cross2eth/ebrelayer/relayer/manager.go index 5bda6c9384..14589a46cd 100644 --- a/plugin/dapp/cross2eth/ebrelayer/relayer/manager.go +++ b/plugin/dapp/cross2eth/ebrelayer/relayer/manager.go @@ -27,14 +27,14 @@ var ( mlog = log15.New("relayer manager", "manager") ) -//status ... +// status ... const ( Locked = int32(1) Unlocked = int32(99) EncryptEnable = int64(1) ) -//Manager ... +// Manager ... type Manager struct { chain33Relayer *chain33.Relayer4Chain33 ethRelayer map[string]*ethereum.Relayer4Ethereum @@ -46,9 +46,9 @@ type Manager struct { decimalLru *lru.Cache } -//NewRelayerManager ... -//1.验证人的私钥需要通过cli命令行进行导入,且chain33和ethereum两种不同的验证人需要分别导入 -//2.显示或者重新替换原有的私钥首先需要通过passpin进行unlock的操作 +// NewRelayerManager ... +// 1.验证人的私钥需要通过cli命令行进行导入,且chain33和ethereum两种不同的验证人需要分别导入 +// 2.显示或者重新替换原有的私钥首先需要通过passpin进行unlock的操作 func NewRelayerManager(chain33Relayer *chain33.Relayer4Chain33, ethRelayers map[string]*ethereum.Relayer4Ethereum, db dbm.DB) *Manager { l, _ := lru.New(4096) manager := &Manager{ @@ -65,7 +65,7 @@ func NewRelayerManager(chain33Relayer *chain33.Relayer4Chain33, ethRelayers map[ return manager } -//SetPassphase ... +// SetPassphase ... func (manager *Manager) SetPassphase(setPasswdReq *relayerTypes.ReqSetPasswd, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -109,7 +109,7 @@ func (manager *Manager) SetPassphase(setPasswdReq *relayerTypes.ReqSetPasswd, re return nil } -//ChangePassphase ... +// ChangePassphase ... func (manager *Manager) ChangePassphase(setPasswdReq *relayerTypes.ReqChangePasswd, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -187,7 +187,7 @@ func (manager *Manager) ChangePassphase(setPasswdReq *relayerTypes.ReqChangePass return nil } -//Unlock 进行unlok操作 +// Unlock 进行unlok操作 func (manager *Manager) Unlock(passphase string, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -225,7 +225,7 @@ func (manager *Manager) Unlock(passphase string, result *interface{}) error { return nil } -//Lock 锁定操作,该操作一旦执行,就不能替换验证人的私钥,需要重新unlock之后才能修改 +// Lock 锁定操作,该操作一旦执行,就不能替换验证人的私钥,需要重新unlock之后才能修改 func (manager *Manager) Lock(param interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -240,7 +240,7 @@ func (manager *Manager) Lock(param interface{}, result *interface{}) error { return nil } -//ImportChain33RelayerPrivateKey 导入chain33relayer验证人的私钥,该私钥实际用于向ethereum提交验证交易时签名使用 +// ImportChain33RelayerPrivateKey 导入chain33relayer验证人的私钥,该私钥实际用于向ethereum提交验证交易时签名使用 func (manager *Manager) ImportChain33RelayerPrivateKey(importKeyReq *relayerTypes.ImportKeyReq, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -261,7 +261,7 @@ func (manager *Manager) ImportChain33RelayerPrivateKey(importKeyReq *relayerType return nil } -//GenerateEthereumPrivateKey 生成以太坊私钥 +// GenerateEthereumPrivateKey 生成以太坊私钥 func (manager *Manager) GenerateEthereumPrivateKey(param interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -304,7 +304,7 @@ func (manager *Manager) ImportEthereumPrivateKey4EthRelayer(privateKey string, r return nil } -//ShowChain33RelayerValidator 显示在chain33中以验证人validator身份进行登录的地址 +// ShowChain33RelayerValidator 显示在chain33中以验证人validator身份进行登录的地址 func (manager *Manager) ShowChain33RelayerValidator(param interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -414,7 +414,7 @@ func (manager *Manager) SafeTransfer4Chain33(para *relayerTypes.SafeTransfer, re return nil } -//Burn ... +// Burn ... func (manager *Manager) Burn(burn *relayerTypes.Burn, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -436,7 +436,7 @@ func (manager *Manager) Burn(burn *relayerTypes.Burn, result *interface{}) error return nil } -//BurnAsync ... +// BurnAsync ... func (manager *Manager) BurnAsync(burn *relayerTypes.Burn, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -534,7 +534,7 @@ func (manager *Manager) LockBTYAssetAsync(lockEthErc20Asset *relayerTypes.LockBT return nil } -//LockEthErc20AssetAsync ... +// LockEthErc20AssetAsync ... func (manager *Manager) LockEthErc20AssetAsync(lockEthErc20Asset *relayerTypes.LockEthErc20, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -556,7 +556,7 @@ func (manager *Manager) LockEthErc20AssetAsync(lockEthErc20Asset *relayerTypes.L return nil } -//LockEthErc20Asset ... +// LockEthErc20Asset ... func (manager *Manager) LockEthErc20Asset(lockEthErc20Asset *relayerTypes.LockEthErc20, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -597,7 +597,7 @@ func (manager *Manager) ShowBalanceLocked(BalanceLockedReq *relayerTypes.Balance return nil } -//GetBalance ... +// GetBalance ... func (manager *Manager) GetBalance(balanceAddr *relayerTypes.BalanceAddr, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -646,7 +646,7 @@ func (manager *Manager) ShowMultiBalance(balanceAddr *relayerTypes.BalanceAddr, return nil } -//ShowBridgeBankAddr ... +// ShowBridgeBankAddr ... func (manager *Manager) ShowBridgeBankAddr(para interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -669,7 +669,7 @@ func (manager *Manager) ShowBridgeBankAddr(para interface{}, result *interface{} return nil } -//ShowBridgeRegistryAddr ... +// ShowBridgeRegistryAddr ... func (manager *Manager) ShowBridgeRegistryAddr(para interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -692,7 +692,7 @@ func (manager *Manager) ShowBridgeRegistryAddr(para interface{}, result *interfa return nil } -//ShowBridgeRegistryAddr4chain33 ... +// ShowBridgeRegistryAddr4chain33 ... func (manager *Manager) ShowBridgeRegistryAddr4chain33(para interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -707,7 +707,7 @@ func (manager *Manager) ShowBridgeRegistryAddr4chain33(para interface{}, result return nil } -//ShowTokenAddress ... +// ShowTokenAddress ... func (manager *Manager) ShowTokenAddress(token2show *relayerTypes.TokenAddress, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -757,7 +757,7 @@ func (manager *Manager) ShowETHLockTokenAddress(token2show *relayerTypes.TokenAd return nil } -//ShowTxReceipt ... +// ShowTxReceipt ... func (manager *Manager) ShowTxReceipt(txReceiptReq *relayerTypes.TxReceiptReq, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -824,7 +824,7 @@ func (manager *Manager) ShowTokenStatics(request *relayerTypes.TokenStaticsReque return nil } -//TransferToken ... +// TransferToken ... func (manager *Manager) TransferToken(transfer *relayerTypes.TransferToken, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -843,7 +843,7 @@ func (manager *Manager) TransferToken(transfer *relayerTypes.TransferToken, resu return nil } -//GetDecimals ... +// GetDecimals ... func (manager *Manager) GetDecimals(chainName, tokenAddr string) (int64, error) { if d, ok := manager.decimalLru.Get(tokenAddr); ok { mlog.Info("GetDecimals", "from cache", d) @@ -899,7 +899,7 @@ func (manager *Manager) SafeTransfer4Eth(para *relayerTypes.SafeTransfer, result return nil } -//TransferEth ... +// TransferEth ... func (manager *Manager) TransferEth(transfer *relayerTypes.TransferToken, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -1085,7 +1085,7 @@ func (manager *Manager) BurnWithIncreaseAsyncFromChain33(burn *relayerTypes.Burn return nil } -//ShowEthRelayerValidator 显示在Ethereum中以验证人validator身份进行登录的地址 +// ShowEthRelayerValidator 显示在Ethereum中以验证人validator身份进行登录的地址 func (manager *Manager) ShowEthRelayerValidator(chainName string, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() diff --git a/plugin/dapp/cross2eth/ebrelayer/types/info.go b/plugin/dapp/cross2eth/ebrelayer/types/info.go index a18571adc7..c65ec36763 100644 --- a/plugin/dapp/cross2eth/ebrelayer/types/info.go +++ b/plugin/dapp/cross2eth/ebrelayer/types/info.go @@ -1,6 +1,6 @@ package types -//Version4Relayer ... +// Version4Relayer ... const Version4Relayer = "0.1.4" const ( diff --git a/plugin/dapp/cross2eth/ebrelayer/types/relayer.pb.go b/plugin/dapp/cross2eth/ebrelayer/types/relayer.pb.go index 0edb2c6174..2ebe75e148 100644 --- a/plugin/dapp/cross2eth/ebrelayer/types/relayer.pb.go +++ b/plugin/dapp/cross2eth/ebrelayer/types/relayer.pb.go @@ -21,9 +21,10 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package -//以太坊账户信息 -// privkey : 账户地址对应的私钥 -// addr :账户地址 +// 以太坊账户信息 +// +// privkey : 账户地址对应的私钥 +// addr :账户地址 type Account4Relayer struct { Privkey []byte `protobuf:"bytes,1,opt,name=privkey,proto3" json:"privkey,omitempty"` Addr string `protobuf:"bytes,2,opt,name=addr,proto3" json:"addr,omitempty"` diff --git a/plugin/dapp/cross2eth/ebrelayer/utils/solsha3.go b/plugin/dapp/cross2eth/ebrelayer/utils/solsha3.go index 33ed710256..f83ca21a6b 100644 --- a/plugin/dapp/cross2eth/ebrelayer/utils/solsha3.go +++ b/plugin/dapp/cross2eth/ebrelayer/utils/solsha3.go @@ -188,7 +188,7 @@ func Uint32(input interface{}) []byte { case uint64: binary.Write(b, binary.BigEndian, uint32(v)) case uint32: - binary.Write(b, binary.BigEndian, uint32(v)) + binary.Write(b, binary.BigEndian, v) case uint16: binary.Write(b, binary.BigEndian, uint32(v)) case uint8: @@ -359,7 +359,7 @@ func Int256(input interface{}) []byte { bn := big.NewInt(int64(v)) return common.LeftPadBytes(bn.Bytes(), 32) case int64: - bn := big.NewInt(int64(v)) + bn := big.NewInt(v) return common.LeftPadBytes(bn.Bytes(), 32) case int32: bn := big.NewInt(int64(v)) @@ -419,7 +419,7 @@ func Int128(input interface{}) []byte { bn := big.NewInt(int64(v)) return common.LeftPadBytes(bn.Bytes(), 16) case int64: - bn := big.NewInt(int64(v)) + bn := big.NewInt(v) return common.LeftPadBytes(bn.Bytes(), 16) case int32: bn := big.NewInt(int64(v)) diff --git a/plugin/dapp/cross2eth/ebrelayer/utils/utils.go b/plugin/dapp/cross2eth/ebrelayer/utils/utils.go index dec5d129a6..f0fe5d85e1 100644 --- a/plugin/dapp/cross2eth/ebrelayer/utils/utils.go +++ b/plugin/dapp/cross2eth/ebrelayer/utils/utils.go @@ -61,7 +61,7 @@ func IsZeroAddress(address common.Address) bool { return address == common.HexToAddress(nullAddress) } -//IsValidPassWord 密码合法性校验,密码长度在8-30位之间。必须是数字+字母的组合 +// IsValidPassWord 密码合法性校验,密码长度在8-30位之间。必须是数字+字母的组合 func IsValidPassWord(password string) bool { pwLen := len(password) if pwLen < 8 || pwLen > 30 { @@ -95,7 +95,7 @@ func decodeInt64(int64bytes []byte) (int64, error) { return value.Data, nil } -//LoadInt64FromDB ... +// LoadInt64FromDB ... func LoadInt64FromDB(key []byte, db dbm.DB) (int64, error) { bytes, err := db.Get(key) if bytes == nil || err != nil { @@ -107,7 +107,7 @@ func LoadInt64FromDB(key []byte, db dbm.DB) (int64, error) { return decodeInt64(bytes) } -//QueryTxhashes ... +// QueryTxhashes ... func QueryTxhashes(prefix []byte, db dbm.DB) []string { kvdb := dbm.NewKVDB(db) hashes, err := kvdb.List(prefix, nil, 10, 1) @@ -122,17 +122,17 @@ func QueryTxhashes(prefix []byte, db dbm.DB) []string { return hashStrs } -//Addr2DecimalsKey ... +// Addr2DecimalsKey ... var ( Addr2DecimalsKey = []byte("prefix_for_Addr2Decimals") ) -//CalAddr2DecimalsPrefix ... +// CalAddr2DecimalsPrefix ... func CalAddr2DecimalsPrefix(tokenAddr string) []byte { return []byte(fmt.Sprintf("%s-%s", Addr2DecimalsKey, tokenAddr)) } -//GetDecimalsFromDB ... +// GetDecimalsFromDB ... func GetDecimalsFromDB(addr string, db dbm.DB) (int64, error) { res, err := db.Get(CalAddr2DecimalsPrefix(addr)) if err != nil { @@ -156,7 +156,7 @@ func SimpleGetDecimals(addr string) (int64, error) { return 8, nil } -//GetDecimalsFromNode ... +// GetDecimalsFromNode ... func GetDecimalsFromNode(addr, rpcLaddr string) (int64, error) { if addr == "0x0000000000000000000000000000000000000000" || addr == "" { return 18, nil @@ -284,7 +284,7 @@ func SendToServer(url string, req io.Reader) ([]byte, error) { } -//MultiplySpecifyTimes ... +// MultiplySpecifyTimes ... func MultiplySpecifyTimes(start float64, time int64) float64 { for i := 0; i < int(time); i++ { start *= 10 @@ -292,7 +292,7 @@ func MultiplySpecifyTimes(start float64, time int64) float64 { return start } -//Toeth ... +// Toeth ... func Toeth(amount string, decimal int64) float64 { bf := big.NewFloat(0) @@ -306,7 +306,7 @@ func Toeth(amount string, decimal int64) float64 { return f } -//ToWei 将eth单位的金额转为wei单位 +// ToWei 将eth单位的金额转为wei单位 func ToWei(amount float64, decimal int64) *big.Int { var ok bool bn := big.NewInt(1) @@ -329,7 +329,7 @@ func SmalToBig(amount float64, decimals uint8) *big.Int { return bn } -//TrimZeroAndDot ... +// TrimZeroAndDot ... func TrimZeroAndDot(s string) string { if strings.Contains(s, ".") { var trimDotStr string @@ -341,7 +341,7 @@ func TrimZeroAndDot(s string) string { return s } -//CheckPower ... +// CheckPower ... func CheckPower(power int64) bool { if power <= 0 || power > 100 { return false @@ -349,7 +349,7 @@ func CheckPower(power int64) bool { return true } -//DivideDot ... +// DivideDot ... func DivideDot(in string) (left, right string, err error) { if strings.Contains(in, ".") { ss := strings.Split(in, ".") @@ -358,7 +358,7 @@ func DivideDot(in string) (left, right string, err error) { return "", "", errors.New("Divide error") } -//IsExecAddrMatch ... +// IsExecAddrMatch ... func IsExecAddrMatch(name string, to string) bool { toaddr := address.ExecAddress(name) return toaddr == to diff --git a/plugin/dapp/cross2eth/ebrelayer/version/version.go b/plugin/dapp/cross2eth/ebrelayer/version/version.go index ff2620161c..201889bd24 100644 --- a/plugin/dapp/cross2eth/ebrelayer/version/version.go +++ b/plugin/dapp/cross2eth/ebrelayer/version/version.go @@ -5,7 +5,7 @@ import ( "runtime" ) -//var version control +// var version control var ( Version = "1.1.0" GitCommit string @@ -16,7 +16,7 @@ var ( Platform = fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH) ) -//GetVersion 获取版本信息 +// GetVersion 获取版本信息 func GetVersion() string { if GitCommit != "" { return Version + "-" + GitCommit diff --git a/plugin/dapp/dex/boss/deploy/chain33/offline/common.go b/plugin/dapp/dex/boss/deploy/chain33/offline/common.go index c9c3b8811c..f2695eb992 100644 --- a/plugin/dapp/dex/boss/deploy/chain33/offline/common.go +++ b/plugin/dapp/dex/boss/deploy/chain33/offline/common.go @@ -53,7 +53,7 @@ func sendSignTxs2Chain33Cmd() *cobra.Command { } func addSendSignTxs2Chain33Flags(cmd *cobra.Command) { - cmd.Flags().StringP("path", "p", "./", "(optional)path of txs file,default to current directroy") + cmd.Flags().StringP("path", "p", "./", "(optional)path of txs file,default to current directory") cmd.Flags().StringP("file", "f", "", "file name which contains the txs to be sent to chain33") _ = cmd.MarkFlagRequired("file") } diff --git a/plugin/dapp/dex/boss/deploy/ethereum/cakeHandler.go b/plugin/dapp/dex/boss/deploy/ethereum/cakeHandler.go index 6f478dc191..eaca6bf4b5 100644 --- a/plugin/dapp/dex/boss/deploy/ethereum/cakeHandler.go +++ b/plugin/dapp/dex/boss/deploy/ethereum/cakeHandler.go @@ -18,12 +18,12 @@ import ( "github.com/ethereum/go-ethereum/ethclient" ) -//var TestNodeAddr = "https://data-seed-prebsc-1-s1.binance.org:8545/" +// var TestNodeAddr = "https://data-seed-prebsc-1-s1.binance.org:8545/" var ethClient *ethclient.Client var privateKey *ecdsa.PrivateKey var deployerAddr common.Address -//const ... +// const ... const ( // GasLimit : the gas limit in Gwei used for transactions sent with TransactOpts GasLimit = uint64(100 * 10000) @@ -90,7 +90,7 @@ func getNonce(sender common.Address) (*big.Int, error) { return big.NewInt(int64(nonce)), nil } -//PrepareAuth ... +// PrepareAuth ... func PrepareAuth(privateKey *ecdsa.PrivateKey, transactor common.Address) (*bind.TransactOpts, error) { //ctx := context.Background() //gasPrice, err := ethClient.SuggestGasPrice(ctx) diff --git a/plugin/dapp/dex/boss/deploy/ethereum/ethCli.go b/plugin/dapp/dex/boss/deploy/ethereum/ethCli.go index 85159a7f32..fd0c6a856a 100644 --- a/plugin/dapp/dex/boss/deploy/ethereum/ethCli.go +++ b/plugin/dapp/dex/boss/deploy/ethereum/ethCli.go @@ -132,7 +132,7 @@ func rewriteDeployErc20(owner, name, symbol, amount string, decimals uint8, nonc return offline.SignTx(key, tx) } -//GetBalanceCmd ... +// GetBalanceCmd ... func GetBalanceCmd() *cobra.Command { cmd := &cobra.Command{ Use: "balance", @@ -143,14 +143,14 @@ func GetBalanceCmd() *cobra.Command { return cmd } -//GetBalanceFlags ... +// GetBalanceFlags ... func GetBalanceFlags(cmd *cobra.Command) { cmd.Flags().StringP("owner", "o", "", "owner address") _ = cmd.MarkFlagRequired("owner") cmd.Flags().StringP("tokenAddr", "t", "", "token address, optional, nil for Eth") } -//GetBalance ... +// GetBalance ... func ShowBalance(cmd *cobra.Command, args []string) { owner, _ := cmd.Flags().GetString("owner") tokenAddr, _ := cmd.Flags().GetString("tokenAddr") diff --git a/plugin/dapp/dex/boss/deploy/ethereum/farmCmd.go b/plugin/dapp/dex/boss/deploy/ethereum/farmCmd.go index 81c9ae8b49..4d8504cbe4 100644 --- a/plugin/dapp/dex/boss/deploy/ethereum/farmCmd.go +++ b/plugin/dapp/dex/boss/deploy/ethereum/farmCmd.go @@ -112,7 +112,7 @@ func ShowCackeBalanceCmd() *cobra.Command { return cmd } -//GetBalanceFlags ... +// GetBalanceFlags ... func ShowBalanceFlags(cmd *cobra.Command) { cmd.Flags().StringP("owner", "o", "", "owner address") _ = cmd.MarkFlagRequired("owner") @@ -122,7 +122,7 @@ func ShowBalanceFlags(cmd *cobra.Command) { } -//GetBalance ... +// GetBalance ... func ShowCakeBalance(cmd *cobra.Command, args []string) { owner, _ := cmd.Flags().GetString("owner") pid, _ := cmd.Flags().GetInt64("pid") diff --git a/plugin/dapp/dex/boss/deploy/ethereum/farmHandler.go b/plugin/dapp/dex/boss/deploy/ethereum/farmHandler.go index be76c9a2a2..bd5a21e773 100644 --- a/plugin/dapp/dex/boss/deploy/ethereum/farmHandler.go +++ b/plugin/dapp/dex/boss/deploy/ethereum/farmHandler.go @@ -146,7 +146,7 @@ func AddPool2FarmHandle(masterChefAddrStr, key string, allocPoint int64, lpToken return err } auth.GasLimit = gasLimit - AddPool2FarmTx, err := masterChefInt.Add(auth, big.NewInt(int64(allocPoint)), common.HexToAddress(lpToken), withUpdate) + AddPool2FarmTx, err := masterChefInt.Add(auth, big.NewInt(allocPoint), common.HexToAddress(lpToken), withUpdate) if err != nil { panic(fmt.Sprintf("Failed to AddPool2FarmTx with err:%s", err.Error())) } diff --git a/plugin/dapp/dex/boss/deploy/ethereum/offline/deployContractCmd.go b/plugin/dapp/dex/boss/deploy/ethereum/offline/deployContractCmd.go index 0a3306ed5f..75452225d3 100644 --- a/plugin/dapp/dex/boss/deploy/ethereum/offline/deployContractCmd.go +++ b/plugin/dapp/dex/boss/deploy/ethereum/offline/deployContractCmd.go @@ -16,7 +16,7 @@ import ( "github.com/spf13/cobra" ) -//SignFactoryCmd 构造部署factory 合约的交易,并对其签名输出到文件中 +// SignFactoryCmd 构造部署factory 合约的交易,并对其签名输出到文件中 type SignCmd struct { From string Nonce uint64 @@ -217,7 +217,7 @@ func (s *SignCmd) signContractTx(fee2setter string, key *ecdsa.PrivateKey, gasPr return nil } -//构造交易,签名交易 factory +// 构造交易,签名交易 factory func (s *SignCmd) reWriteDeplopyPancakeFactory(nonce uint64, gasPrice *big.Int, key *ecdsa.PrivateKey, fee2addr common.Address, param ...interface{}) (signedTx, hash string, err error) { parsed, err := abi.JSON(strings.NewReader(pancakeFactory.PancakeFactoryABI)) if err != nil { @@ -238,13 +238,13 @@ func (s *SignCmd) reWriteDeplopyPancakeFactory(nonce uint64, gasPrice *big.Int, type SignWeth9Cmd struct { } -//only sign Weth9 +// only sign Weth9 func (s *SignWeth9Cmd) reWriteDeployWETH9(nonce uint64, gasPrice *big.Int, key *ecdsa.PrivateKey, param ...interface{}) (signedTx, hash string, err error) { parsed, err := abi.JSON(strings.NewReader(pancakeRouter.WETH9ABI)) if err != nil { return "", "", err } - input, err := parsed.Pack("", param...) + input, _ := parsed.Pack("", param...) abiBin := pancakeRouter.WETH9Bin data := append(common.FromHex(abiBin), input...) var amount = new(big.Int) diff --git a/plugin/dapp/dex/boss/deploy/ethereum/offline/poolCmd.go b/plugin/dapp/dex/boss/deploy/ethereum/offline/poolCmd.go index ac8b8b216c..4c586b7101 100644 --- a/plugin/dapp/dex/boss/deploy/ethereum/offline/poolCmd.go +++ b/plugin/dapp/dex/boss/deploy/ethereum/offline/poolCmd.go @@ -98,7 +98,7 @@ func (a *AddPool) AddPool2Farm(cmd *cobra.Command, args []string) { func (a *AddPool) reWriteAddPool2Farm(nonce uint64, masterChefAddrStr string, gasPrice *big.Int, key *ecdsa.PrivateKey) (signedTx, hash string, err error) { masterChefAddr := common.HexToAddress(masterChefAddrStr) - parsed, err := abi.JSON(strings.NewReader(masterChef.MasterChefABI)) + parsed, _ := abi.JSON(strings.NewReader(masterChef.MasterChefABI)) input, err := parsed.Pack("add", big.NewInt(a.allocPoint), common.HexToAddress(a.lpToken), a.withUpdate) if err != nil { panic(err) @@ -185,7 +185,7 @@ func (u *updateAllocPoint) updateAllocPointCmdFlags(cmd *cobra.Command) { func (u *updateAllocPoint) rewriteUpdateAllocPoint(masterChefAddrStr string, nonce uint64, gasPrice *big.Int, key *ecdsa.PrivateKey) (signedTx, hash string, err error) { masterChefAddr := common.HexToAddress(masterChefAddrStr) - parsed, err := abi.JSON(strings.NewReader(masterChef.MasterChefABI)) + parsed, _ := abi.JSON(strings.NewReader(masterChef.MasterChefABI)) input, err := parsed.Pack("set", big.NewInt(u.pid), big.NewInt(u.allocPoint), u.withUpdate) if err != nil { panic(err) @@ -258,7 +258,7 @@ func (t *transferOwnerShip) TransferOwnerShip(cmd *cobra.Command, args []string) func TransferOwnerShipHandle(nonce uint64, gasPrice *big.Int, newOwner, contract string, key *ecdsa.PrivateKey) (signedtx, hash string, err error) { contractAddr := common.HexToAddress(contract) newOwnerAddr := common.HexToAddress(newOwner) - parsed, err := abi.JSON(strings.NewReader(syrupBar.SyrupBarABI)) + parsed, _ := abi.JSON(strings.NewReader(syrupBar.SyrupBarABI)) input, err := parsed.Pack("transferOwnership", newOwnerAddr) if err != nil { return diff --git a/plugin/dapp/dex/boss/deploy/ethereum/offline/query.go b/plugin/dapp/dex/boss/deploy/ethereum/offline/query.go index 985755aca8..0c203eb183 100644 --- a/plugin/dapp/dex/boss/deploy/ethereum/offline/query.go +++ b/plugin/dapp/dex/boss/deploy/ethereum/offline/query.go @@ -57,7 +57,6 @@ func (q *queryCmd) query(cmd *cobra.Command, args []string) { info.Nonce = nonce info.Timestamp = time.Now().Format(time.RFC3339) writeToFile("accountinfo.txt", &info) - return } diff --git a/plugin/dapp/dposvote/commands/vote.go b/plugin/dapp/dposvote/commands/vote.go index e898db672e..794821c61f 100644 --- a/plugin/dapp/dposvote/commands/vote.go +++ b/plugin/dapp/dposvote/commands/vote.go @@ -787,8 +787,8 @@ func evaluate(cmd *cobra.Command, args []string) { vrfHash, vrfProof := vrfPriv.Evaluate(m) fmt.Println("vrf evaluate:") fmt.Println("input:", data) - fmt.Println(fmt.Sprintf("hash:%x", vrfHash)) - fmt.Println(fmt.Sprintf("proof:%x", vrfProof)) + fmt.Printf("hash:%x\n", vrfHash) + fmt.Printf("proof:%x\n", vrfProof) } // DPosCBRecordCmd to create keyfiles diff --git a/plugin/dapp/dposvote/executor/dposvote.go b/plugin/dapp/dposvote/executor/dposvote.go index 3344861b8f..68475f517c 100644 --- a/plugin/dapp/dposvote/executor/dposvote.go +++ b/plugin/dapp/dposvote/executor/dposvote.go @@ -70,13 +70,13 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&DPos{})) } -//DPos 执行器,用于Dpos候选节点注册、投票,VRF信息注册管理等功能 +// DPos 执行器,用于Dpos候选节点注册、投票,VRF信息注册管理等功能 type DPos struct { drivers.DriverBase } @@ -88,17 +88,17 @@ func newDposVote() drivers.Driver { return t } -//GetName 获取DPos执行器的名称 +// GetName 获取DPos执行器的名称 func GetName() string { return newDposVote().GetName() } -//ExecutorOrder Exec 的时候 同时执行 ExecLocal +// ExecutorOrder Exec 的时候 同时执行 ExecLocal func (g *DPos) ExecutorOrder() int64 { return drivers.ExecLocalSameTime } -//GetDriverName 获取DPos执行器的名称 +// GetDriverName 获取DPos执行器的名称 func (g *DPos) GetDriverName() string { return dty.DPosX } diff --git a/plugin/dapp/dposvote/executor/dposvotedb.go b/plugin/dapp/dposvote/executor/dposvotedb.go index d6f5accc23..1c1e8a2b71 100644 --- a/plugin/dapp/dposvote/executor/dposvotedb.go +++ b/plugin/dapp/dposvote/executor/dposvotedb.go @@ -31,7 +31,7 @@ const ( DefaultCount = int32(10) ) -//Action 具体动作执行 +// Action 具体动作执行 type Action struct { coinsAccount *account.DB db dbm.KV @@ -45,7 +45,7 @@ type Action struct { mainHeight int64 } -//NewAction 生成Action对象 +// NewAction 生成Action对象 func NewAction(dpos *DPos, tx *types.Transaction, index int) *Action { hash := tx.Hash() fromAddr := tx.From() @@ -64,7 +64,7 @@ func NewAction(dpos *DPos, tx *types.Transaction, index int) *Action { } } -//CheckExecAccountBalance 检查地址在Dpos合约中的余额是否足够 +// CheckExecAccountBalance 检查地址在Dpos合约中的余额是否足够 func (action *Action) CheckExecAccountBalance(fromAddr string, ToFrozen, ToActive int64) bool { acc := action.coinsAccount.LoadExecAccount(fromAddr, action.execaddr) if acc.GetBalance() >= ToFrozen && acc.GetFrozen() >= ToActive { @@ -73,7 +73,7 @@ func (action *Action) CheckExecAccountBalance(fromAddr string, ToFrozen, ToActiv return false } -//Key State数据库中存储记录的Key值格式转换 +// Key State数据库中存储记录的Key值格式转换 func Key(id string) (key []byte) { //key = append(key, []byte("mavl-"+types.ExecName(pkt.GuessX)+"-")...) key = append(key, []byte("mavl-"+dty.DPosX+"-")...) @@ -81,14 +81,14 @@ func Key(id string) (key []byte) { return key } -//TopNKey State数据库中存储记录的Key值格式转换 +// TopNKey State数据库中存储记录的Key值格式转换 func TopNKey(id string) (key []byte) { key = append(key, []byte("mavl-"+dty.DPosX+"-"+"topn"+"-")...) key = append(key, []byte(id)...) return key } -//queryVrfByTime 根据时间信息,查询TopN的受托节点的VRF信息 +// queryVrfByTime 根据时间信息,查询TopN的受托节点的VRF信息 func queryVrfByTime(kvdb db.KVDB, req *dty.DposVrfQuery) (types.Message, error) { if req.Ty != dty.QueryVrfByTime { return nil, types.ErrInvalidParam @@ -170,7 +170,7 @@ func getVrfInfoFromVrfM(vrfM *dty.DposVrfM) *dty.VrfInfo { return vrf } -//queryVrfByCycleAndPubkeys 根据Cycle、Pubkeys信息,查询受托节点的VRF信息 +// queryVrfByCycleAndPubkeys 根据Cycle、Pubkeys信息,查询受托节点的VRF信息 func queryVrfByCycleAndPubkeys(kvdb db.KVDB, pubkeys []string, cycle int64) []*dty.VrfInfo { VrfRPTable := dty.NewDposVrfRPTable(kvdb) query := VrfRPTable.GetQuery(kvdb) @@ -211,7 +211,7 @@ func queryVrfByCycleAndPubkeys(kvdb db.KVDB, pubkeys []string, cycle int64) []*d return vrfs } -//queryVrfByCycleForPubkeys 根据Cycle、Pubkeys信息,查询受托节点的VRF信息 +// queryVrfByCycleForPubkeys 根据Cycle、Pubkeys信息,查询受托节点的VRF信息 func queryVrfByCycleForPubkeys(kvdb db.KVDB, req *dty.DposVrfQuery) (types.Message, error) { if req.Ty != dty.QueryVrfByCycleForPubkeys { return nil, types.ErrInvalidParam @@ -222,7 +222,7 @@ func queryVrfByCycleForPubkeys(kvdb db.KVDB, req *dty.DposVrfQuery) (types.Messa return &dty.DposVrfReply{Vrf: getJSONVrfs(vrfs)}, nil } -//queryVrfByCycleForTopN 根据Cycle信息,查询TopN的受托节点的VRF信息 +// queryVrfByCycleForTopN 根据Cycle信息,查询TopN的受托节点的VRF信息 func queryVrfByCycleForTopN(kvdb db.KVDB, req *dty.DposVrfQuery) (types.Message, error) { if req.Ty != dty.QueryVrfByCycleForTopN { return nil, types.ErrInvalidParam @@ -251,7 +251,7 @@ func queryVrfByCycleForTopN(kvdb db.KVDB, req *dty.DposVrfQuery) (types.Message, return &dty.DposVrfReply{Vrf: getJSONVrfs(vrfs)}, nil } -//queryVrfByCycle 根据Cycle信息,查询所有受托节点的VRF信息 +// queryVrfByCycle 根据Cycle信息,查询所有受托节点的VRF信息 func queryVrfByCycle(kvdb db.KVDB, req *dty.DposVrfQuery) (types.Message, error) { if req.Ty != dty.QueryVrfByCycle { return nil, types.ErrInvalidParam @@ -290,7 +290,7 @@ func queryVrfByCycle(kvdb db.KVDB, req *dty.DposVrfQuery) (types.Message, error) return &dty.DposVrfReply{Vrf: getJSONVrfs(vrfs)}, nil } -//queryCands 根据候选节点的Pubkey下旬候选节点信息,得票数、状态等 +// queryCands 根据候选节点的Pubkey下旬候选节点信息,得票数、状态等 func queryCands(kvdb db.KVDB, req *dty.CandidatorQuery) (types.Message, error) { var cands []*dty.JSONCandidator candTable := dty.NewDposCandidatorTable(kvdb) @@ -316,7 +316,7 @@ func queryCands(kvdb db.KVDB, req *dty.CandidatorQuery) (types.Message, error) { return &dty.CandidatorReply{Candidators: cands}, nil } -//queryTopNCands 查询得票数TopN的候选节点信息,包括得票数,状态等 +// queryTopNCands 查询得票数TopN的候选节点信息,包括得票数,状态等 func queryTopNCands(kvdb db.KVDB, req *dty.CandidatorQuery) (types.Message, error) { var cands []*dty.JSONCandidator candTable := dty.NewDposCandidatorTable(kvdb) @@ -389,7 +389,7 @@ func queryTopNCands(kvdb db.KVDB, req *dty.CandidatorQuery) (types.Message, erro return &dty.CandidatorReply{Candidators: cands}, nil } -//isValidPubkey 判断一个公钥是否属于一个公钥集合 +// isValidPubkey 判断一个公钥是否属于一个公钥集合 func isValidPubkey(pubkeys []string, pubkey string) bool { if len(pubkeys) == 0 || len(pubkey) == 0 { return false @@ -404,7 +404,7 @@ func isValidPubkey(pubkeys []string, pubkey string) bool { return false } -//queryVote 根据用户地址信息查询用户的投票情况 +// queryVote 根据用户地址信息查询用户的投票情况 func queryVote(kvdb db.KVDB, req *dty.DposVoteQuery) (types.Message, error) { var voters []*dty.JSONDposVoter voteTable := dty.NewDposVoteTable(kvdb) @@ -458,7 +458,7 @@ func (action *Action) getIndex() int64 { return action.height*types.MaxTxsPerBlock + int64(action.index) } -//getReceiptLog 根据候选节点信息及投票信息生成收据信息 +// getReceiptLog 根据候选节点信息及投票信息生成收据信息 func (action *Action) getReceiptLog(candInfo *dty.CandidatorInfo, statusChange bool, voteType int32, vote *dty.DposVoter) *types.ReceiptLog { log := &types.ReceiptLog{} r := &dty.ReceiptCandicator{} @@ -498,7 +498,7 @@ func (action *Action) getReceiptLog(candInfo *dty.CandidatorInfo, statusChange b return log } -//readCandicatorInfo 根据候选节点的公钥查询候选节点信息 +// readCandicatorInfo 根据候选节点的公钥查询候选节点信息 func (action *Action) readCandicatorInfo(pubkey []byte) (*dty.CandidatorInfo, error) { strPubkey := hex.EncodeToString(pubkey) data, err := action.db.Get(Key(strPubkey)) @@ -527,7 +527,7 @@ func (action *Action) newCandicatorInfo(regist *dty.DposCandidatorRegist) *dty.C return candInfo } -//readTopNCandicators 根据版本信息查询特定高度区间的TOPN候选节点信息 +// readTopNCandicators 根据版本信息查询特定高度区间的TOPN候选节点信息 func (action *Action) readTopNCandicators(version int64) (*dty.TopNCandidators, error) { strVersion := fmt.Sprintf("%018d", version) data, err := action.db.Get(TopNKey(strVersion)) @@ -556,7 +556,7 @@ func (action *Action) saveTopNCandicators(topCands *dty.TopNCandidators) (kvset return kvset } -//queryCBInfoByCycle 根据cycle查询stopHeight及stopHash等CBInfo信息,用于VRF计算 +// queryCBInfoByCycle 根据cycle查询stopHeight及stopHash等CBInfo信息,用于VRF计算 func queryCBInfoByCycle(kvdb db.KVDB, req *dty.DposCBQuery) (types.Message, error) { cbTable := dty.NewDposCBTable(kvdb) query := cbTable.GetQuery(kvdb) @@ -580,7 +580,7 @@ func queryCBInfoByCycle(kvdb db.KVDB, req *dty.DposCBQuery) (types.Message, erro return &dty.DposCBReply{CbInfo: info}, nil } -//queryCBInfoByHeight 根据stopHeight查询stopHash等CBInfo信息,用于VRF计算 +// queryCBInfoByHeight 根据stopHeight查询stopHash等CBInfo信息,用于VRF计算 func queryCBInfoByHeight(kvdb db.KVDB, req *dty.DposCBQuery) (types.Message, error) { cbTable := dty.NewDposCBTable(kvdb) query := cbTable.GetQuery(kvdb) @@ -604,7 +604,7 @@ func queryCBInfoByHeight(kvdb db.KVDB, req *dty.DposCBQuery) (types.Message, err return &dty.DposCBReply{CbInfo: info}, nil } -//queryCBInfoByHash 根据stopHash查询CBInfo信息,用于VRF计算 +// queryCBInfoByHash 根据stopHash查询CBInfo信息,用于VRF计算 func queryCBInfoByHash(kvdb db.KVDB, req *dty.DposCBQuery) (types.Message, error) { cbTable := dty.NewDposCBTable(kvdb) query := cbTable.GetQuery(kvdb) @@ -635,7 +635,7 @@ func queryCBInfoByHash(kvdb db.KVDB, req *dty.DposCBQuery) (types.Message, error return &dty.DposCBReply{CbInfo: info}, nil } -//queryTopNByVersion 根据version查询具体周期使用的TopN超级节点信息 +// queryTopNByVersion 根据version查询具体周期使用的TopN超级节点信息 func queryTopNByVersion(db dbm.KV, req *dty.TopNCandidatorsQuery) (types.Message, error) { strVersion := fmt.Sprintf("%018d", req.Version) data, err := db.Get(TopNKey(strVersion)) @@ -658,7 +658,7 @@ func queryTopNByVersion(db dbm.KV, req *dty.TopNCandidatorsQuery) (types.Message return reply, nil } -//Regist 注册候选节点 +// Regist 注册候选节点 func (action *Action) Regist(regist *dty.DposCandidatorRegist) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -711,7 +711,7 @@ func (action *Action) Regist(regist *dty.DposCandidatorRegist) (*types.Receipt, return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//ReRegist 重新注册一个注销的候选节点 +// ReRegist 重新注册一个注销的候选节点 func (action *Action) ReRegist(regist *dty.DposCandidatorRegist) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -774,7 +774,7 @@ func (action *Action) ReRegist(regist *dty.DposCandidatorRegist) (*types.Receipt return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//CancelRegist 撤销一个候选节点的注册 +// CancelRegist 撤销一个候选节点的注册 func (action *Action) CancelRegist(req *dty.DposCandidatorCancelRegist) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -846,7 +846,7 @@ func (action *Action) CancelRegist(req *dty.DposCandidatorCancelRegist) (*types. return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//Vote 为某一个候选节点投票 +// Vote 为某一个候选节点投票 func (action *Action) Vote(vote *dty.DposVote) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -913,7 +913,7 @@ func (action *Action) Vote(vote *dty.DposVote) (*types.Receipt, error) { return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//CancelVote 撤销对某个候选节点的投票 +// CancelVote 撤销对某个候选节点的投票 func (action *Action) CancelVote(vote *dty.DposCancelVote) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -974,7 +974,7 @@ func (action *Action) CancelVote(vote *dty.DposCancelVote) (*types.Receipt, erro return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//RegistVrfM 注册受托节点的Vrf M信息(输入信息) +// RegistVrfM 注册受托节点的Vrf M信息(输入信息) func (action *Action) RegistVrfM(vrfMReg *dty.DposVrfMRegist) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -1055,7 +1055,7 @@ func (action *Action) RegistVrfM(vrfMReg *dty.DposVrfMRegist) (*types.Receipt, e return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//RegistVrfRP 注册受托节点的Vrf R/P信息 +// RegistVrfRP 注册受托节点的Vrf R/P信息 func (action *Action) RegistVrfRP(vrfRPReg *dty.DposVrfRPRegist) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -1141,7 +1141,7 @@ func (action *Action) RegistVrfRP(vrfRPReg *dty.DposVrfRPRegist) (*types.Receipt return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//RecordCB 记录cycle boundary info +// RecordCB 记录cycle boundary info func (action *Action) RecordCB(cbInfo *dty.DposCBInfo) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -1211,7 +1211,7 @@ func (action *Action) RecordCB(cbInfo *dty.DposCBInfo) (*types.Receipt, error) { return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//RegistTopN 注册TopN节点 +// RegistTopN 注册TopN节点 func (action *Action) RegistTopN(regist *dty.TopNCandidatorRegist) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue diff --git a/plugin/dapp/dposvote/executor/exec_del_local.go b/plugin/dapp/dposvote/executor/exec_del_local.go index fa37684bc1..905046cdc2 100644 --- a/plugin/dapp/dposvote/executor/exec_del_local.go +++ b/plugin/dapp/dposvote/executor/exec_del_local.go @@ -221,47 +221,47 @@ func (d *DPos) execDelLocal(receipt *types.ReceiptData) (*types.LocalDBSet, erro return dbSet, nil } -//ExecDelLocal_Regist method +// ExecDelLocal_Regist method func (d *DPos) ExecDelLocal_Regist(payload *dty.DposCandidatorRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execDelLocal(receiptData) } -//ExecDelLocal_CancelRegist method +// ExecDelLocal_CancelRegist method func (d *DPos) ExecDelLocal_CancelRegist(payload *dty.DposCandidatorCancelRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execDelLocal(receiptData) } -//ExecDelLocal_ReRegist method +// ExecDelLocal_ReRegist method func (d *DPos) ExecDelLocal_ReRegist(payload *dty.DposCandidatorRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execDelLocal(receiptData) } -//ExecDelLocal_Vote method +// ExecDelLocal_Vote method func (d *DPos) ExecDelLocal_Vote(payload *dty.DposVote, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execDelLocal(receiptData) } -//ExecDelLocal_CancelVote method +// ExecDelLocal_CancelVote method func (d *DPos) ExecDelLocal_CancelVote(payload *dty.DposCancelVote, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execDelLocal(receiptData) } -//ExecDelLocal_VrfMRegist method +// ExecDelLocal_VrfMRegist method func (d *DPos) ExecDelLocal_VrfMRegist(payload *dty.DposVrfMRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execDelLocal(receiptData) } -//ExecDelLocal_VrfRPRegist method +// ExecDelLocal_VrfRPRegist method func (d *DPos) ExecDelLocal_VrfRPRegist(payload *dty.DposVrfRPRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execDelLocal(receiptData) } -//ExecDelLocal_RecordCB method +// ExecDelLocal_RecordCB method func (d *DPos) ExecDelLocal_RecordCB(payload *dty.DposCBInfo, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execDelLocal(receiptData) } -//ExecDelLocal_RegistTopN method +// ExecDelLocal_RegistTopN method func (d *DPos) ExecDelLocal_RegistTopN(payload *dty.TopNCandidatorRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execDelLocal(receiptData) } diff --git a/plugin/dapp/dposvote/executor/exec_local.go b/plugin/dapp/dposvote/executor/exec_local.go index f07394dc1f..6a701ff4e4 100644 --- a/plugin/dapp/dposvote/executor/exec_local.go +++ b/plugin/dapp/dposvote/executor/exec_local.go @@ -218,47 +218,47 @@ func (d *DPos) execLocal(receipt *types.ReceiptData) (*types.LocalDBSet, error) return dbSet, nil } -//ExecLocal_Regist method +// ExecLocal_Regist method func (d *DPos) ExecLocal_Regist(payload *dty.DposCandidatorRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execLocal(receiptData) } -//ExecLocal_CancelRegist method +// ExecLocal_CancelRegist method func (d *DPos) ExecLocal_CancelRegist(payload *dty.DposCandidatorCancelRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execLocal(receiptData) } -//ExecLocal_ReRegist method +// ExecLocal_ReRegist method func (d *DPos) ExecLocal_ReRegist(payload *dty.DposCandidatorRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execLocal(receiptData) } -//ExecLocal_Vote method +// ExecLocal_Vote method func (d *DPos) ExecLocal_Vote(payload *dty.DposVote, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execLocal(receiptData) } -//ExecLocal_CancelVote method +// ExecLocal_CancelVote method func (d *DPos) ExecLocal_CancelVote(payload *dty.DposCancelVote, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execLocal(receiptData) } -//ExecLocal_RegistVrfM method +// ExecLocal_RegistVrfM method func (d *DPos) ExecLocal_RegistVrfM(payload *dty.DposVrfMRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execLocal(receiptData) } -//ExecLocal_RegistVrfRP method +// ExecLocal_RegistVrfRP method func (d *DPos) ExecLocal_RegistVrfRP(payload *dty.DposVrfRPRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execLocal(receiptData) } -//ExecLocal_RecordCB method +// ExecLocal_RecordCB method func (d *DPos) ExecLocal_RecordCB(payload *dty.DposCBInfo, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execLocal(receiptData) } -//ExecLocal_RegistTopN method +// ExecLocal_RegistTopN method func (d *DPos) ExecLocal_RegistTopN(payload *dty.TopNCandidatorRegist, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return d.execLocal(receiptData) } diff --git a/plugin/dapp/dposvote/executor/query.go b/plugin/dapp/dposvote/executor/query.go index e07afbe459..ed06ed8400 100644 --- a/plugin/dapp/dposvote/executor/query.go +++ b/plugin/dapp/dposvote/executor/query.go @@ -9,57 +9,57 @@ import ( dty "github.com/33cn/plugin/plugin/dapp/dposvote/types" ) -//Query_QueryCandidatorByPubkeys method +// Query_QueryCandidatorByPubkeys method func (d *DPos) Query_QueryCandidatorByPubkeys(in *dty.CandidatorQuery) (types.Message, error) { return queryCands(d.GetLocalDB(), in) } -//Query_QueryCandidatorByTopN method +// Query_QueryCandidatorByTopN method func (d *DPos) Query_QueryCandidatorByTopN(in *dty.CandidatorQuery) (types.Message, error) { return queryTopNCands(d.GetLocalDB(), in) } -//Query_QueryVote method +// Query_QueryVote method func (d *DPos) Query_QueryVote(in *dty.DposVoteQuery) (types.Message, error) { return queryVote(d.GetLocalDB(), in) } -//Query_QueryVrfByTime method +// Query_QueryVrfByTime method func (d *DPos) Query_QueryVrfByTime(in *dty.DposVrfQuery) (types.Message, error) { return queryVrfByTime(d.GetLocalDB(), in) } -//Query_QueryVrfByCycle method +// Query_QueryVrfByCycle method func (d *DPos) Query_QueryVrfByCycle(in *dty.DposVrfQuery) (types.Message, error) { return queryVrfByCycle(d.GetLocalDB(), in) } -//Query_QueryVrfByCycleForTopN method +// Query_QueryVrfByCycleForTopN method func (d *DPos) Query_QueryVrfByCycleForTopN(in *dty.DposVrfQuery) (types.Message, error) { return queryVrfByCycleForTopN(d.GetLocalDB(), in) } -//Query_QueryVrfByCycleForPubkeys method +// Query_QueryVrfByCycleForPubkeys method func (d *DPos) Query_QueryVrfByCycleForPubkeys(in *dty.DposVrfQuery) (types.Message, error) { return queryVrfByCycleForPubkeys(d.GetLocalDB(), in) } -//Query_QueryCBInfoByCycle method +// Query_QueryCBInfoByCycle method func (d *DPos) Query_QueryCBInfoByCycle(in *dty.DposCBQuery) (types.Message, error) { return queryCBInfoByCycle(d.GetLocalDB(), in) } -//Query_QueryCBInfoByHeight method +// Query_QueryCBInfoByHeight method func (d *DPos) Query_QueryCBInfoByHeight(in *dty.DposCBQuery) (types.Message, error) { return queryCBInfoByHeight(d.GetLocalDB(), in) } -//Query_QueryCBInfoByHash method +// Query_QueryCBInfoByHash method func (d *DPos) Query_QueryCBInfoByHash(in *dty.DposCBQuery) (types.Message, error) { return queryCBInfoByHash(d.GetLocalDB(), in) } -//Query_QueryTopNByVersion method +// Query_QueryTopNByVersion method func (d *DPos) Query_QueryTopNByVersion(in *dty.TopNCandidatorsQuery) (types.Message, error) { return queryTopNByVersion(d.GetStateDB(), in) } diff --git a/plugin/dapp/dposvote/types/const.go b/plugin/dapp/dposvote/types/const.go index a1c05b3c43..d8425545d4 100644 --- a/plugin/dapp/dposvote/types/const.go +++ b/plugin/dapp/dposvote/types/const.go @@ -4,7 +4,7 @@ package types -//dpos action ty +// dpos action ty const ( DposVoteActionRegist = iota + 1 DposVoteActionCancelRegist @@ -30,7 +30,7 @@ const ( TopNCandidatorStatusRegist = iota + 1 ) -//log ty +// log ty const ( TyLogCandicatorRegist = 1001 TyLogCandicatorVoted = 1002 @@ -71,9 +71,9 @@ const ( TopNCandidatorsVoteMajorFail int64 = 2 ) -//包的名字可以通过配置文件来配置 -//建议用github的组织名称,或者用户名字开头, 再加上自己的插件的名字 -//如果发生重名,可以通过配置文件修改这些名字 +// 包的名字可以通过配置文件来配置 +// 建议用github的组织名称,或者用户名字开头, 再加上自己的插件的名字 +// 如果发生重名,可以通过配置文件修改这些名字 var ( DPosX = "dpos" ExecerDposVote = []byte(DPosX) diff --git a/plugin/dapp/dposvote/types/msg.go b/plugin/dapp/dposvote/types/msg.go index d12a01eb99..e6a6bf1215 100644 --- a/plugin/dapp/dposvote/types/msg.go +++ b/plugin/dapp/dposvote/types/msg.go @@ -136,9 +136,7 @@ func (topN *TopNCandidator) copyWithoutSig() *TopNCandidator { } cpy.Cands = make([]*Candidator, len(topN.Cands)) - for i := 0; i < len(topN.Cands); i++ { - cpy.Cands[i] = topN.Cands[i] - } + copy(cpy.Cands, topN.Cands) return cpy } diff --git a/plugin/dapp/dposvote/types/table.go b/plugin/dapp/dposvote/types/table.go index 3573d62eff..dc4d6b51f3 100644 --- a/plugin/dapp/dposvote/types/table.go +++ b/plugin/dapp/dposvote/types/table.go @@ -22,7 +22,7 @@ var optDposVoter = &table.Option{ Index: []string{"addr", "pubkey"}, } -//NewDposVoteTable 新建表 +// NewDposVoteTable 新建表 func NewDposVoteTable(kvdb db.KV) *table.Table { rowmeta := NewDposVoterRow() table, err := table.NewTable(rowmeta, kvdb, optDposVoter) @@ -32,22 +32,22 @@ func NewDposVoteTable(kvdb db.KV) *table.Table { return table } -//DposVoterRow table meta 结构 +// DposVoterRow table meta 结构 type DposVoterRow struct { *DposVoter } -//NewDposVoterRow 新建一个meta 结构 +// NewDposVoterRow 新建一个meta 结构 func NewDposVoterRow() *DposVoterRow { return &DposVoterRow{DposVoter: &DposVoter{}} } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (tx *DposVoterRow) CreateRow() *table.Row { return &table.Row{Data: &DposVoter{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (tx *DposVoterRow) SetPayload(data types.Message) error { if txdata, ok := data.(*DposVoter); ok { tx.DposVoter = txdata @@ -56,7 +56,7 @@ func (tx *DposVoterRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (tx *DposVoterRow) Get(key string) ([]byte, error) { if key == "index" { return []byte(fmt.Sprintf("%018d", tx.Index)), nil @@ -76,7 +76,7 @@ var optDposCandidator = &table.Option{ Index: []string{"status"}, } -//NewDposCandidatorTable 新建表 +// NewDposCandidatorTable 新建表 func NewDposCandidatorTable(kvdb db.KV) *table.Table { rowmeta := NewDposCandidatorRow() table, err := table.NewTable(rowmeta, kvdb, optDposCandidator) @@ -86,22 +86,22 @@ func NewDposCandidatorTable(kvdb db.KV) *table.Table { return table } -//DposCandidatorRow table meta 结构 +// DposCandidatorRow table meta 结构 type DposCandidatorRow struct { *CandidatorInfo } -//NewDposCandidatorRow 新建一个meta 结构 +// NewDposCandidatorRow 新建一个meta 结构 func NewDposCandidatorRow() *DposCandidatorRow { return &DposCandidatorRow{CandidatorInfo: &CandidatorInfo{}} } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (tx *DposCandidatorRow) CreateRow() *table.Row { return &table.Row{Data: &CandidatorInfo{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (tx *DposCandidatorRow) SetPayload(data types.Message) error { if txdata, ok := data.(*CandidatorInfo); ok { tx.CandidatorInfo = txdata @@ -110,7 +110,7 @@ func (tx *DposCandidatorRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (tx *DposCandidatorRow) Get(key string) ([]byte, error) { if key == "pubkey" { return tx.Pubkey, nil @@ -128,7 +128,7 @@ var optDposVrfm = &table.Option{ Index: []string{"pubkey_cycle", "cycle"}, } -//NewDposVrfMTable 新建表 +// NewDposVrfMTable 新建表 func NewDposVrfMTable(kvdb db.KV) *table.Table { rowmeta := NewDposVrfMRow() table, err := table.NewTable(rowmeta, kvdb, optDposVrfm) @@ -138,22 +138,22 @@ func NewDposVrfMTable(kvdb db.KV) *table.Table { return table } -//DposVrfMRow table meta 结构 +// DposVrfMRow table meta 结构 type DposVrfMRow struct { *DposVrfM } -//NewDposVrfMRow 新建一个meta 结构 +// NewDposVrfMRow 新建一个meta 结构 func NewDposVrfMRow() *DposVrfMRow { return &DposVrfMRow{DposVrfM: &DposVrfM{}} } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (tx *DposVrfMRow) CreateRow() *table.Row { return &table.Row{Data: &DposVrfM{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (tx *DposVrfMRow) SetPayload(data types.Message) error { if txdata, ok := data.(*DposVrfM); ok { tx.DposVrfM = txdata @@ -162,7 +162,7 @@ func (tx *DposVrfMRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (tx *DposVrfMRow) Get(key string) ([]byte, error) { if key == "index" { return []byte(fmt.Sprintf("%018d", tx.Index)), nil @@ -182,7 +182,7 @@ var optDposVrfrp = &table.Option{ Index: []string{"pubkey_cycle", "cycle"}, } -//NewDposVrfRPTable 新建表 +// NewDposVrfRPTable 新建表 func NewDposVrfRPTable(kvdb db.KV) *table.Table { rowmeta := NewDposVrfRPRow() table, err := table.NewTable(rowmeta, kvdb, optDposVrfrp) @@ -192,22 +192,22 @@ func NewDposVrfRPTable(kvdb db.KV) *table.Table { return table } -//DposVrfRPRow table meta 结构 +// DposVrfRPRow table meta 结构 type DposVrfRPRow struct { *DposVrfRP } -//NewDposVrfRPRow 新建一个meta 结构 +// NewDposVrfRPRow 新建一个meta 结构 func NewDposVrfRPRow() *DposVrfRPRow { return &DposVrfRPRow{DposVrfRP: &DposVrfRP{}} } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (tx *DposVrfRPRow) CreateRow() *table.Row { return &table.Row{Data: &DposVrfRP{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (tx *DposVrfRPRow) SetPayload(data types.Message) error { if txdata, ok := data.(*DposVrfRP); ok { tx.DposVrfRP = txdata @@ -216,7 +216,7 @@ func (tx *DposVrfRPRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (tx *DposVrfRPRow) Get(key string) ([]byte, error) { if key == "index" { return []byte(fmt.Sprintf("%018d", tx.Index)), nil @@ -236,7 +236,7 @@ var optDposCb = &table.Option{ Index: []string{"height", "hash"}, } -//NewDposCBTable 新建表 +// NewDposCBTable 新建表 func NewDposCBTable(kvdb db.KV) *table.Table { rowmeta := NewDposCBRow() table, err := table.NewTable(rowmeta, kvdb, optDposCb) @@ -246,22 +246,22 @@ func NewDposCBTable(kvdb db.KV) *table.Table { return table } -//DposCBRow table meta 结构 +// DposCBRow table meta 结构 type DposCBRow struct { *DposCycleBoundaryInfo } -//NewDposCBRow 新建一个meta 结构 +// NewDposCBRow 新建一个meta 结构 func NewDposCBRow() *DposCBRow { return &DposCBRow{DposCycleBoundaryInfo: &DposCycleBoundaryInfo{}} } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (tx *DposCBRow) CreateRow() *table.Row { return &table.Row{Data: &DposCycleBoundaryInfo{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (tx *DposCBRow) SetPayload(data types.Message) error { if txdata, ok := data.(*DposCycleBoundaryInfo); ok { tx.DposCycleBoundaryInfo = txdata @@ -270,7 +270,7 @@ func (tx *DposCBRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (tx *DposCBRow) Get(key string) ([]byte, error) { if key == "cycle" { return []byte(fmt.Sprintf("%018d", tx.Cycle)), nil diff --git a/plugin/dapp/dposvote/types/types.go b/plugin/dapp/dposvote/types/types.go index 578d77b6a9..6b4b22512f 100644 --- a/plugin/dapp/dposvote/types/types.go +++ b/plugin/dapp/dposvote/types/types.go @@ -17,12 +17,12 @@ func init() { types.RegExec(DPosX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(DPosX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(DPosX, NewType(cfg)) } diff --git a/plugin/dapp/echo/types/echo/echo.pb.go b/plugin/dapp/echo/types/echo/echo.pb.go index 72a67a50d7..33fd81299e 100644 --- a/plugin/dapp/echo/types/echo/echo.pb.go +++ b/plugin/dapp/echo/types/echo/echo.pb.go @@ -5,9 +5,11 @@ Package echo is a generated protocol buffer package. It is generated from these files: + echo.proto It has these top-level messages: + Ping Pang EchoAction diff --git a/plugin/dapp/echo/types/echo/types.go b/plugin/dapp/echo/types/echo/types.go index 66f3ead93b..ce34a50421 100644 --- a/plugin/dapp/echo/types/echo/types.go +++ b/plugin/dapp/echo/types/echo/types.go @@ -42,12 +42,12 @@ func init() { types.RegExec(EchoX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(EchoX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(EchoX, NewType(cfg)) } diff --git a/plugin/dapp/evm/commands/evm.go b/plugin/dapp/evm/commands/evm.go index e864135487..c2e9c90315 100644 --- a/plugin/dapp/evm/commands/evm.go +++ b/plugin/dapp/evm/commands/evm.go @@ -31,7 +31,7 @@ import ( "github.com/spf13/cobra" ) -//EvmCmd 是Evm命令行入口 +// EvmCmd 是Evm命令行入口 func EvmCmd() *cobra.Command { cmd := &cobra.Command{ Use: "evm", @@ -94,16 +94,16 @@ func transferAddress(cmd *cobra.Command, args []string) { fmt.Println(fmt.Errorf("ethereum address is invalid: %v", eth)) return } - fmt.Println(fmt.Sprintf("Ethereum Address: %v", eth)) - fmt.Println(fmt.Sprintf("Local Address: %v", evmCommon.BytesToAddress(data).String())) + fmt.Printf("Ethereum Address: %v\n", eth) + fmt.Printf("Local Address: %v\n", evmCommon.BytesToAddress(data).String()) return } if len(local) >= 34 { var addr evmCommon.Address if strings.HasPrefix(local, evmtypes.EvmPrefix) { addr = evmCommon.ExecAddress(local) - fmt.Println(fmt.Sprintf("Local Contract Name: %v", local)) - fmt.Println(fmt.Sprintf("Local Address: %v", addr.String())) + fmt.Printf("Local Contract Name: %v\n", local) + fmt.Printf("Local Address: %v\n", addr.String()) } else { addrP := evmCommon.StringToAddress(local) if addrP == nil { @@ -111,9 +111,9 @@ func transferAddress(cmd *cobra.Command, args []string) { return } addr = *addrP - fmt.Println(fmt.Sprintf("Local Address: %v", local)) + fmt.Printf("Local Address: %v\n", local) } - fmt.Println(fmt.Sprintf("Ethereum Address: %v", checksumAddr(addr.Bytes()))) + fmt.Printf("Ethereum Address: %v\n", checksumAddr(addr.Bytes())) return } @@ -204,7 +204,7 @@ func parseGetBalanceRes(arg ...interface{}) (interface{}, error) { func calcNewContractAddrCmd() *cobra.Command { cmd := &cobra.Command{ Use: "calc", - Short: "calulate new contract address", + Short: "calculate new contract address", Run: calcNewContractAddr, } addCalcNewContractAddrFlags(cmd) diff --git a/plugin/dapp/evm/executor/abi/abi_test.go b/plugin/dapp/evm/executor/abi/abi_test.go index 13ceefb1b3..8d7a885b48 100644 --- a/plugin/dapp/evm/executor/abi/abi_test.go +++ b/plugin/dapp/evm/executor/abi/abi_test.go @@ -164,8 +164,9 @@ func TestInvalidABI(t *testing.T) { // TestConstructor tests a constructor function. // The test is based on the following contract: -// contract TestConstructor { -// constructor(uint256 a, uint256 b) public{} +// +// contract TestConstructor { +// constructor(uint256 a, uint256 b) public{} // } func TestConstructor(t *testing.T) { json := `[{ "inputs": [{"internalType": "uint256","name": "a","type": "uint256" },{ "internalType": "uint256","name": "b","type": "uint256"}],"stateMutability": "nonpayable","type": "constructor"}]` @@ -712,16 +713,19 @@ func TestBareEvents(t *testing.T) { } // TestUnpackEvent is based on this contract: -// contract T { -// event received(address sender, uint amount, bytes memo); -// event receivedAddr(address sender); -// function receive(bytes memo) external payable { -// received(msg.sender, msg.value, memo); -// receivedAddr(msg.sender); -// } -// } +// +// contract T { +// event received(address sender, uint amount, bytes memo); +// event receivedAddr(address sender); +// function receive(bytes memo) external payable { +// received(msg.sender, msg.value, memo); +// receivedAddr(msg.sender); +// } +// } +// // When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt: -// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]} +// +// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]} func TestUnpackEvent(t *testing.T) { const abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]` abi, err := JSON(strings.NewReader(abiJSON)) @@ -1068,8 +1072,9 @@ func TestDoubleDuplicateMethodNames(t *testing.T) { // TestDoubleDuplicateEventNames checks that if send0 already exists, there won't be a name // conflict and that the second send event will be renamed send1. // The test runs the abi of the following contract. -// contract DuplicateEvent { -// event send(uint256 a); +// +// contract DuplicateEvent { +// event send(uint256 a); // event send0(); // event send(); // } @@ -1096,7 +1101,8 @@ func TestDoubleDuplicateEventNames(t *testing.T) { // TestUnnamedEventParam checks that an event with unnamed parameters is // correctly handled // The test runs the abi of the following contract. -// contract TestEvent { +// +// contract TestEvent { // event send(uint256, uint256); // } func TestUnnamedEventParam(t *testing.T) { diff --git a/plugin/dapp/evm/executor/abi/api.go b/plugin/dapp/evm/executor/abi/api.go index a05fa2d02e..54b4f4d0ca 100644 --- a/plugin/dapp/evm/executor/abi/api.go +++ b/plugin/dapp/evm/executor/abi/api.go @@ -152,7 +152,7 @@ func Unpack(data []byte, methodName, abiData string) (output []*Param, err error return } -//同时支持input,output和event三种数据的unpack +// 同时支持input,output和event三种数据的unpack func UnpackAllTypes(data []byte, name, abiData string) (output []*Param, err error) { if len(data) == 0 { log.Info("Unpack", "Data len", 0, "name", name) diff --git a/plugin/dapp/evm/executor/abi/reflect.go b/plugin/dapp/evm/executor/abi/reflect.go index 75f1a00a5a..1ea481ec29 100644 --- a/plugin/dapp/evm/executor/abi/reflect.go +++ b/plugin/dapp/evm/executor/abi/reflect.go @@ -152,10 +152,14 @@ func setStruct(dst, src reflect.Value) error { // mapArgNamesToStructFields maps a slice of argument names to struct fields. // first round: for each Exportable field that contains a `abi:""` tag -// and this field name exists in the given argument name list, pair them together. +// +// and this field name exists in the given argument name list, pair them together. +// // second round: for each argument name that has not been already linked, -// find what variable is expected to be mapped into, if it exists and has not been -// used, pair them. +// +// find what variable is expected to be mapped into, if it exists and has not been +// used, pair them. +// // Note this function assumes the given value is a struct value. func mapArgNamesToStructFields(argNames []string, value reflect.Value) (map[string]string, error) { typ := value.Type() diff --git a/plugin/dapp/evm/executor/attack_integration_test.go b/plugin/dapp/evm/executor/attack_integration_test.go index 18ab647287..8b30834971 100644 --- a/plugin/dapp/evm/executor/attack_integration_test.go +++ b/plugin/dapp/evm/executor/attack_integration_test.go @@ -202,7 +202,7 @@ func TestWBTYOverflowAttackIntegration(t *testing.T) { t.Logf("✓ victim deposited %d into pool", poolValue) // 攻击者 withdraw - wdInput := vcomm.FromHex("2e1a7d4d") // withdraw(uint256) + wdInput := vcomm.FromHex("2e1a7d4d") // withdraw(uint256) amt7M := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x6a, 0xc7, 0x60, 0x00} // 7,000,000 as uint256 wdInput = append(wdInput, amt7M...) r, err = exec.Exec(makeCallTx(cfg, roleAttacker, contractAddr, wdInput, 0), 0) diff --git a/plugin/dapp/evm/executor/query_test.go b/plugin/dapp/evm/executor/query_test.go index d4afaf2701..dd5ebb4e9e 100644 --- a/plugin/dapp/evm/executor/query_test.go +++ b/plugin/dapp/evm/executor/query_test.go @@ -7,12 +7,12 @@ import ( "strings" "testing" - "github.com/BurntSushi/toml" apimock "github.com/33cn/chain33/client/mocks" "github.com/33cn/chain33/common/address" dbm "github.com/33cn/chain33/common/db" cty "github.com/33cn/chain33/system/dapp/coins/types" vcomm "github.com/33cn/plugin/plugin/dapp/evm/executor/vm/common" + "github.com/BurntSushi/toml" dbmock "github.com/33cn/chain33/common/db/mocks" ctypes "github.com/33cn/chain33/types" @@ -248,33 +248,33 @@ func TestQuickEstimateGasValue(t *testing.T) { expect uint64 }{ { - name: "nil default", - toml: ``, + name: "nil default", + toml: ``, expect: 1300, }, { - name: "float from toml", - toml: `gasmultiple = 2.0`, + name: "float from toml", + toml: `gasmultiple = 2.0`, expect: 2000, }, { - name: "int from toml", - toml: `gasmultiple = 2`, + name: "int from toml", + toml: `gasmultiple = 2`, expect: 2000, }, { - name: "below 1.0 clamped", - toml: `gasmultiple = 0.5`, + name: "below 1.0 clamped", + toml: `gasmultiple = 0.5`, expect: 1000, }, { - name: "exactly 1.0", - toml: `gasmultiple = 1.0`, + name: "exactly 1.0", + toml: `gasmultiple = 1.0`, expect: 1000, }, { - name: "invalid string fallback", - toml: `gasmultiple = "invalid"`, + name: "invalid string fallback", + toml: `gasmultiple = "invalid"`, expect: 1300, }, } diff --git a/plugin/dapp/evm/executor/vm/common/address.go b/plugin/dapp/evm/executor/vm/common/address.go index f2f942196e..14d8d602f1 100644 --- a/plugin/dapp/evm/executor/vm/common/address.go +++ b/plugin/dapp/evm/executor/vm/common/address.go @@ -151,7 +151,7 @@ func NewContractAddress(b Address, txHash []byte) Address { return PubKey2Address(execPub) } -//NewEvmContractAddress 通过nonce创建合约地址 +// NewEvmContractAddress 通过nonce创建合约地址 func NewEvmContractAddress(b Address, nonce uint64) Address { execAddr := ethcrypto.CreateAddress(common.BytesToAddress(b.Bytes()), nonce) var a Address diff --git a/plugin/dapp/evm/executor/vm/common/big.go b/plugin/dapp/evm/executor/vm/common/big.go index d397c98410..e27c0cb575 100644 --- a/plugin/dapp/evm/executor/vm/common/big.go +++ b/plugin/dapp/evm/executor/vm/common/big.go @@ -67,10 +67,11 @@ func U256(x *big.Int) *big.Int { // S256 interprets x as a two's complement number. // x must not exceed 256 bits (the result is undefined if it does) and is not modified. -// S256(0) = 0 -// S256(1) = 1 -// S256(2**255) = -2**255 -// S256(2**256-1) = -1 +// +// S256(0) = 0 +// S256(1) = 1 +// S256(2**255) = -2**255 +// S256(2**256-1) = -1 func S256(x *big.Int) *big.Int { if x.Cmp(TT255) < 0 { return x diff --git a/plugin/dapp/evm/executor/vm/common/crypto/bn256/cloudflare/constants.go b/plugin/dapp/evm/executor/vm/common/crypto/bn256/cloudflare/constants.go index b8fa32ed52..14296266f4 100644 --- a/plugin/dapp/evm/executor/vm/common/crypto/bn256/cloudflare/constants.go +++ b/plugin/dapp/evm/executor/vm/common/crypto/bn256/cloudflare/constants.go @@ -1,6 +1,7 @@ // Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +// //nolint:unparam // 忽视本文件所有golangci-linter检查 package bn256 diff --git a/plugin/dapp/evm/executor/vm/common/crypto/bn256/cloudflare/example_test.go b/plugin/dapp/evm/executor/vm/common/crypto/bn256/cloudflare/example_test.go index 7ed130af2f..6c0972d551 100644 --- a/plugin/dapp/evm/executor/vm/common/crypto/bn256/cloudflare/example_test.go +++ b/plugin/dapp/evm/executor/vm/common/crypto/bn256/cloudflare/example_test.go @@ -1,6 +1,7 @@ // Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +// //nolint:unparam // 忽视本文件所有golangci-linter检查 package bn256 diff --git a/plugin/dapp/evm/executor/vm/common/math/big.go b/plugin/dapp/evm/executor/vm/common/math/big.go index 17a57df9dc..966b3ea240 100644 --- a/plugin/dapp/evm/executor/vm/common/math/big.go +++ b/plugin/dapp/evm/executor/vm/common/math/big.go @@ -193,10 +193,10 @@ func U256Bytes(n *big.Int) []byte { // S256 interprets x as a two's complement number. // x must not exceed 256 bits (the result is undefined if it does) and is not modified. // -// S256(0) = 0 -// S256(1) = 1 -// S256(2**255) = -2**255 -// S256(2**256-1) = -1 +// S256(0) = 0 +// S256(1) = 1 +// S256(2**255) = -2**255 +// S256(2**256-1) = -1 func S256(x *big.Int) *big.Int { if x.Cmp(tt255) < 0 { return x diff --git a/plugin/dapp/evm/executor/vm/gas/gas.go b/plugin/dapp/evm/executor/vm/gas/gas.go index d6c7921940..a4013e72ff 100644 --- a/plugin/dapp/evm/executor/vm/gas/gas.go +++ b/plugin/dapp/evm/executor/vm/gas/gas.go @@ -28,7 +28,8 @@ const ( ) // 返回真实花费的Gas -// availableGas - base * 63 / 64. +// +// availableGas - base * 63 / 64. func callGas(gasTable Table, availableGas, base uint64, callCost *uint256.Int) (uint64, error) { if availableGas == callCost.Uint64() { availableGas = availableGas - base diff --git a/plugin/dapp/evm/executor/vm/mm/memory_table.go b/plugin/dapp/evm/executor/vm/mm/memory_table.go index f3cf744d1a..6ee9321d94 100644 --- a/plugin/dapp/evm/executor/vm/mm/memory_table.go +++ b/plugin/dapp/evm/executor/vm/mm/memory_table.go @@ -11,47 +11,47 @@ type ( MemorySizeFunc func(*Stack) (size uint64, overflow bool) ) -//MemorySha3 sha3计算所需内存大小 +// MemorySha3 sha3计算所需内存大小 func MemorySha3(stack *Stack) (uint64, bool) { return calcMemSize64(stack.Back(0), stack.Back(1)) } -//MemoryCallDataCopy callDataCopy所需内存大小 +// MemoryCallDataCopy callDataCopy所需内存大小 func MemoryCallDataCopy(stack *Stack) (uint64, bool) { return calcMemSize64(stack.Back(0), stack.Back(2)) } -//MemoryReturnDataCopy returnDataCopy所需内存大小 +// MemoryReturnDataCopy returnDataCopy所需内存大小 func MemoryReturnDataCopy(stack *Stack) (uint64, bool) { return calcMemSize64(stack.Back(0), stack.Back(2)) } -//MemoryCodeCopy codeCopy所需内存大小 +// MemoryCodeCopy codeCopy所需内存大小 func MemoryCodeCopy(stack *Stack) (uint64, bool) { return calcMemSize64(stack.Back(0), stack.Back(2)) } -//MemoryExtCodeCopy extCodeCopy所需内存大小 +// MemoryExtCodeCopy extCodeCopy所需内存大小 func MemoryExtCodeCopy(stack *Stack) (uint64, bool) { return calcMemSize64(stack.Back(1), stack.Back(3)) } -//MemoryMLoad mload所需内存大小 +// MemoryMLoad mload所需内存大小 func MemoryMLoad(stack *Stack) (uint64, bool) { return calcMemSize64WithUint(stack.Back(0), 32) } -//MemoryMStore8 mstore8所需内存大小 +// MemoryMStore8 mstore8所需内存大小 func MemoryMStore8(stack *Stack) (uint64, bool) { return calcMemSize64WithUint(stack.Back(0), 1) } -//MemoryMStore mstore所需内存大小 +// MemoryMStore mstore所需内存大小 func MemoryMStore(stack *Stack) (uint64, bool) { return calcMemSize64WithUint(stack.Back(0), 32) } -//MemoryCreate create所需内存大小 +// MemoryCreate create所需内存大小 func MemoryCreate(stack *Stack) (uint64, bool) { return calcMemSize64(stack.Back(1), stack.Back(2)) } @@ -60,7 +60,7 @@ func MemoryCreate(stack *Stack) (uint64, bool) { // return calcMemSize64(stack.Back(1), stack.Back(2)) //} -//MemoryCall call所需内存大小 +// MemoryCall call所需内存大小 func MemoryCall(stack *Stack) (uint64, bool) { x, overflow := calcMemSize64(stack.Back(5), stack.Back(6)) if overflow { @@ -76,7 +76,7 @@ func MemoryCall(stack *Stack) (uint64, bool) { return y, false } -//MemoryDelegateCall delegateCall所需内存大小 +// MemoryDelegateCall delegateCall所需内存大小 func MemoryDelegateCall(stack *Stack) (uint64, bool) { x, overflow := calcMemSize64(stack.Back(4), stack.Back(5)) if overflow { @@ -92,7 +92,7 @@ func MemoryDelegateCall(stack *Stack) (uint64, bool) { return y, false } -//MemoryStaticCall staticCall所需内存大小 +// MemoryStaticCall staticCall所需内存大小 func MemoryStaticCall(stack *Stack) (uint64, bool) { x, overflow := calcMemSize64(stack.Back(4), stack.Back(5)) if overflow { @@ -108,17 +108,17 @@ func MemoryStaticCall(stack *Stack) (uint64, bool) { return y, false } -//MemoryReturn return所需内存大小 +// MemoryReturn return所需内存大小 func MemoryReturn(stack *Stack) (uint64, bool) { return calcMemSize64(stack.Back(0), stack.Back(1)) } -//MemoryRevert revert所需内存大小 +// MemoryRevert revert所需内存大小 func MemoryRevert(stack *Stack) (uint64, bool) { return calcMemSize64(stack.Back(0), stack.Back(1)) } -//MemoryLog log所需内存大小 +// MemoryLog log所需内存大小 func MemoryLog(stack *Stack) (uint64, bool) { return calcMemSize64(stack.Back(0), stack.Back(1)) } diff --git a/plugin/dapp/evm/executor/vm/runtime/contracts.go b/plugin/dapp/evm/executor/vm/runtime/contracts.go index 935dccbc07..8c4487a61a 100644 --- a/plugin/dapp/evm/executor/vm/runtime/contracts.go +++ b/plugin/dapp/evm/executor/vm/runtime/contracts.go @@ -87,7 +87,7 @@ var PrecompiledContractsYoloV1 = map[common.Hash160Address]PrecompiledContract{ common.BytesToHash160Address([]byte{18}): &bls12381MapG2{}, } -//因为common.Address结构体中定义的是指针,map中的key值不能使用address作为key值来使用,于是使用Hash160Address作为key来进行索引 +// 因为common.Address结构体中定义的是指针,map中的key值不能使用address作为key值来使用,于是使用Hash160Address作为key来进行索引 // PrecompiledContractsBerlin contains the default set of pre-compiled Ethereum // contracts used in the Berlin release. var PrecompiledContractsBerlin = map[common.Hash160Address]PrecompiledContract{ @@ -255,9 +255,10 @@ var ( // modexpMultComplexity implements bigModexp multComplexity formula, as defined in EIP-198 // // def mult_complexity(x): -// if x <= 64: return x ** 2 -// elif x <= 1024: return x ** 2 // 4 + 96 * x - 3072 -// else: return x ** 2 // 16 + 480 * x - 199680 +// +// if x <= 64: return x ** 2 +// elif x <= 1024: return x ** 2 // 4 + 96 * x - 3072 +// else: return x ** 2 // 16 + 480 * x - 199680 // // where is x is max(length_of_MODULUS, length_of_BASE) func modexpMultComplexity(x *big.Int) *big.Int { diff --git a/plugin/dapp/evm/executor/vm/runtime/contracts_test.go b/plugin/dapp/evm/executor/vm/runtime/contracts_test.go index 797a548281..6c64c7547b 100644 --- a/plugin/dapp/evm/executor/vm/runtime/contracts_test.go +++ b/plugin/dapp/evm/executor/vm/runtime/contracts_test.go @@ -182,7 +182,7 @@ func benchmarkPrecompiled(addr string, test precompiledTest, bench *testing.B) { return } if hex.EncodeToString(res) != test.Expected { - bench.Error(fmt.Sprintf("Expected %v, got %v", test.Expected, hex.EncodeToString(res))) + bench.Errorf("Expected %v, got %v", test.Expected, hex.EncodeToString(res)) return } }) diff --git a/plugin/dapp/evm/executor/vm/runtime/customizeContracts.go b/plugin/dapp/evm/executor/vm/runtime/customizeContracts.go index cf204287ca..006802b135 100644 --- a/plugin/dapp/evm/executor/vm/runtime/customizeContracts.go +++ b/plugin/dapp/evm/executor/vm/runtime/customizeContracts.go @@ -4,10 +4,10 @@ import ( "github.com/33cn/plugin/plugin/dapp/evm/executor/vm/common" ) -//TOKEN 预编译地址 +// TOKEN 预编译地址 const TokenPrecompileAddr = "0x0000000000000000000000000000000000200001" -//其他复杂合约下的预编译地址 +// 其他复杂合约下的预编译地址 const ComflixPrecompileAddr = "0x0000000000000000000000000000000000200002" //TODO 添加新的 GO 合约地址 @@ -15,14 +15,14 @@ const ComflixPrecompileAddr = "0x0000000000000000000000000000000000200002" // CustomizePrecompiledContracts 存储自定义的预编译地址 var CustomizePrecompiledContracts = map[common.Hash160Address]StatefulPrecompiledContract{} -//StatefulPrecompiledContract precompile contract interface +// StatefulPrecompiledContract precompile contract interface type StatefulPrecompiledContract interface { // 计算当前合约执行需要消耗的Gas RequiredGas(input []byte) uint64 Run(evm *EVM, caller ContractRef, input []byte, suppliedGas uint64) (ret []byte, remainingGas uint64, err error) } -//RunStateFulPrecompiledContract 调用自定义的预编译的合约逻辑并返回结果 +// RunStateFulPrecompiledContract 调用自定义的预编译的合约逻辑并返回结果 func RunStateFulPrecompiledContract(evm *EVM, caller ContractRef, sp StatefulPrecompiledContract, input []byte, suppliedGas uint64) (ret []byte, remainingGas uint64, err error) { ret, remainingGas, err = sp.Run(evm, caller, input, suppliedGas) return diff --git a/plugin/dapp/evm/executor/vm/runtime/evm.go b/plugin/dapp/evm/executor/vm/runtime/evm.go index abc5b5e8db..9e54b9a4b4 100644 --- a/plugin/dapp/evm/executor/vm/runtime/evm.go +++ b/plugin/dapp/evm/executor/vm/runtime/evm.go @@ -36,9 +36,9 @@ func run(evm *EVM, contract *Contract, input []byte, readOnly bool) (ret []byte, if contract.CodeAddr != nil { p, sp, _ := evm.precompile(*contract.CodeAddr) if p != nil { - ret, contract.Gas, err = RunPrecompiledContract(p, input, contract.Gas) + _, contract.Gas, _ = RunPrecompiledContract(p, input, contract.Gas) } else if sp != nil { - ret, contract.Gas, err = RunStateFulPrecompiledContract(evm, contract, sp, input, contract.Gas) + _, contract.Gas, _ = RunStateFulPrecompiledContract(evm, contract, sp, input, contract.Gas) } } // 在此处打印下自定义合约的错误信息 diff --git a/plugin/dapp/evm/executor/vm/runtime/instructions.go b/plugin/dapp/evm/executor/vm/runtime/instructions.go index 2ec29ef959..0471356b0a 100644 --- a/plugin/dapp/evm/executor/vm/runtime/instructions.go +++ b/plugin/dapp/evm/executor/vm/runtime/instructions.go @@ -245,7 +245,7 @@ func opSAR(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { return nil, nil } -//使用keccak256进行哈希运算 +// 使用keccak256进行哈希运算 func opSha3(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { offset, size := callContext.stack.pop(), callContext.stack.peek() data := callContext.memory.GetPtr(int64(offset.Uint64()), int64(size.Uint64())) @@ -676,7 +676,7 @@ func opCreate(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { return nil, nil } -//CREATE2 +// CREATE2 func opCreate2(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { var ( endowment = callContext.stack.pop() diff --git a/plugin/dapp/evm/executor/vm/runtime/logger.go b/plugin/dapp/evm/executor/vm/runtime/logger.go index 199771869d..503ddf0f90 100644 --- a/plugin/dapp/evm/executor/vm/runtime/logger.go +++ b/plugin/dapp/evm/executor/vm/runtime/logger.go @@ -130,7 +130,7 @@ func formatMemory(data []byte) (res []string) { return } -//CaptureFault 目前实现为空 +// CaptureFault 目前实现为空 func (logger *JSONLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error { return nil } diff --git a/plugin/dapp/evm/executor/vm/runtime/token.go b/plugin/dapp/evm/executor/vm/runtime/token.go index 13fe68fe9c..99f272801e 100644 --- a/plugin/dapp/evm/executor/vm/runtime/token.go +++ b/plugin/dapp/evm/executor/vm/runtime/token.go @@ -24,12 +24,12 @@ const ( const tokenExecer = "token" -//TokenContract token 合约 +// TokenContract token 合约 type TokenContract struct { SuperManager []string `json:"superManager,omitempty"` } -//NewTokenPrecompile ... +// NewTokenPrecompile ... func NewTokenPrecompile(tokeninfo *TokenContract) StatefulPrecompiledContract { call := &tokenPrecompile{} call.contractInfo = make(map[string]string) @@ -69,7 +69,7 @@ func (t *tokenPrecompile) checkCreator(evm *EVM, caller ContractRef) bool { return false } -//setTokenSymbol 把token下币种的名称缓存起来 +// setTokenSymbol 把token下币种的名称缓存起来 func (t *tokenPrecompile) setTokenSymbol(evm *EVM, caller ContractRef) { t.cacheLock.Lock() defer t.cacheLock.Unlock() @@ -99,7 +99,7 @@ func (t *tokenPrecompile) setTokenSymbol(evm *EVM, caller ContractRef) { log.Error("token.Precompiled setTokenSymbol", "err:", err) } -//Run ... +// Run ... func (t *tokenPrecompile) Run(evm *EVM, caller ContractRef, input []byte, suppliedGas uint64) (ret []byte, remainingGas uint64, err error) { log.Info("token.Precompiled", "Run.Caller", caller.Address().String(), "inputSize:", len(input)) if !t.checkCreator(evm, caller) { diff --git a/plugin/dapp/evm/executor/vm/state/statedb.go b/plugin/dapp/evm/executor/vm/state/statedb.go index 704aed0311..9df4d0adb2 100644 --- a/plugin/dapp/evm/executor/vm/state/statedb.go +++ b/plugin/dapp/evm/executor/vm/state/statedb.go @@ -154,7 +154,7 @@ func (mdb *MemoryStateDB) GetBalance(addr string) uint64 { return uint64(ac.GetBalance()) } -//GetAccountNonce 获取普通地址下的nonce,用于兼容eth签名交易 +// GetAccountNonce 获取普通地址下的nonce,用于兼容eth签名交易 func (mdb *MemoryStateDB) GetAccountNonce(addr string) uint64 { //增加合约账户信息 nonceV, _ := mdb.LocalDB.Get(secp256k1eth.CaculCoinsEvmAccountKey(addr)) @@ -531,7 +531,7 @@ func (mdb *MemoryStateDB) Transfer(sender, recipient string, amount uint64) bool return true } -//TransferToToken evm call token +// TransferToToken evm call token func (mdb *MemoryStateDB) TransferToToken(from, recipient, symbol string, amount int64) (bool, error) { tokenInfo, err := mdb.tokenStatus(symbol) if err != nil { @@ -566,7 +566,7 @@ func (mdb *MemoryStateDB) TransferToToken(from, recipient, symbol string, amount } -//TokenBalance 查询token 账户下的余额 +// TokenBalance 查询token 账户下的余额 func (mdb *MemoryStateDB) TokenBalance(caller common.Address, execer, tokensymbol string) (int64, error) { tokenAccount, err := account.NewAccountDB(mdb.GetConfig(), execer, tokensymbol, mdb.StateDB) if err != nil { @@ -579,7 +579,7 @@ func (mdb *MemoryStateDB) TokenBalance(caller common.Address, execer, tokensymbo return acc.Balance, nil } -//tokenStatus 获取token 状态信息 +// tokenStatus 获取token 状态信息 func (mdb *MemoryStateDB) tokenStatus(tokensymbol string) (*tokenty.LocalToken, error) { tokenPreCreatedSTONewLocal := "LODB-token-create-sto-" tokenKey := []byte(fmt.Sprintf(tokenPreCreatedSTONewLocal+"%d-%s-", 1, tokensymbol)) @@ -598,7 +598,7 @@ func (mdb *MemoryStateDB) tokenStatus(tokensymbol string) (*tokenty.LocalToken, return &tokenInfo, nil } -//TokenSupply 获取token 总量 +// TokenSupply 获取token 总量 func (mdb *MemoryStateDB) TokenSupply(tokensymbol string) (int64, error) { tokenInfo, err := mdb.tokenStatus(tokensymbol) if err != nil { @@ -774,7 +774,7 @@ func (mdb *MemoryStateDB) GetConfig() *types.Chain33Config { return mdb.api.GetConfig() } -//GetApi return QueueProtocolAPI +// GetApi return QueueProtocolAPI func (mdb *MemoryStateDB) GetApi() client.QueueProtocolAPI { return mdb.api } diff --git a/plugin/dapp/evm/types/evmcontract.pb.go b/plugin/dapp/evm/types/evmcontract.pb.go index bca76c40f8..d64b4ce0c5 100644 --- a/plugin/dapp/evm/types/evmcontract.pb.go +++ b/plugin/dapp/evm/types/evmcontract.pb.go @@ -21,7 +21,7 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -//合约对象信息 +// 合约对象信息 type EVMContractObject struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/evmxgo/executor/exec_local.go b/plugin/dapp/evmxgo/executor/exec_local.go index 8be6fe57a7..8615280cf8 100644 --- a/plugin/dapp/evmxgo/executor/exec_local.go +++ b/plugin/dapp/evmxgo/executor/exec_local.go @@ -229,7 +229,7 @@ func (e *evmxgo) ExecLocal_BurnMap(payload *evmxgotypes.EvmxgoBurnMap, tx *types return e.ExecLocal_Burn(pay, tx, receiptData, index) } -//当区块回滚时,框架支持自动回滚localdb kv,需要对exec-local返回的kv进行封装 +// 当区块回滚时,框架支持自动回滚localdb kv,需要对exec-local返回的kv进行封装 func (e *evmxgo) addAutoRollBack(tx *types.Transaction, kv []*types.KeyValue) *types.LocalDBSet { dbSet := &types.LocalDBSet{} diff --git a/plugin/dapp/evmxgo/executor/kv.go b/plugin/dapp/evmxgo/executor/kv.go index 8f90fb371f..4ee336b5d1 100644 --- a/plugin/dapp/evmxgo/executor/kv.go +++ b/plugin/dapp/evmxgo/executor/kv.go @@ -33,7 +33,7 @@ func calcEvmxgoStatusKeyLocal(token string) []byte { return []byte(fmt.Sprintf(evmxgoCreatedSTONewLocal+"%s", token)) } -//存储地址上收币的信息 +// 存储地址上收币的信息 func calcAddrKey(token string, addr string) []byte { return []byte(fmt.Sprintf("LODB-evmxgo-%s-Addr:%s", token, address.FormatAddrKey(addr))) } diff --git a/plugin/dapp/evmxgo/executor/parse.go b/plugin/dapp/evmxgo/executor/parse.go index eb379e5920..468976ddf8 100644 --- a/plugin/dapp/evmxgo/executor/parse.go +++ b/plugin/dapp/evmxgo/executor/parse.go @@ -18,8 +18,8 @@ const ( LockMethod = "lock" ) -//solidity interface: function lock(address _recipient, address _token, uint256 _amount) -//铸币交易的接收人必须与发起lock交易时填写的接收地址一致 +// solidity interface: function lock(address _recipient, address _token, uint256 _amount) +// 铸币交易的接收人必须与发起lock交易时填写的接收地址一致 func checkMintPara(mint *evmxgotypes.EvmxgoMint, tx2lock *types.Transaction, db dbm.KV) error { bridgevmxgoConfig, err := loadBridgevmxgoAddr(db) if nil != err { diff --git a/plugin/dapp/exchange/client/exchange.go b/plugin/dapp/exchange/client/exchange.go index 2e3caa1816..db06b6e3d8 100755 --- a/plugin/dapp/exchange/client/exchange.go +++ b/plugin/dapp/exchange/client/exchange.go @@ -96,7 +96,7 @@ func (c *ExchangeClient) LimitOrder(msg proto.Message, hexKey string) (*et.Recei return &resp, nil } -//TODO marketOrder +// TODO marketOrder func (c *ExchangeClient) MarketOrder(msg proto.Message, hexKey string) (*et.ReceiptExchange, error) { return nil, errors.New("Unopen") //ety := types.LoadExecutorType(et.ExchangeX) diff --git a/plugin/dapp/exchange/client/grpc_cli.go b/plugin/dapp/exchange/client/grpc_cli.go index 51b1890891..42a65ba417 100755 --- a/plugin/dapp/exchange/client/grpc_cli.go +++ b/plugin/dapp/exchange/client/grpc_cli.go @@ -96,7 +96,7 @@ func (c *GRPCCli) sendAndWaitReceipt(tx *types.Transaction, hexKey string) (logs return d.Receipt.Logs, nil } -//SendTx ...s +// SendTx ...s func (c *GRPCCli) sendTx(tx *types.Transaction, hexKey string) (reply *types.Reply, err error) { cfg := types.NewChain33Config(types.GetDefaultCfgstring()) cfg.SetTitleOnlyForTest("chain33") diff --git a/plugin/dapp/exchange/executor/exchange.go b/plugin/dapp/exchange/executor/exchange.go index d787956542..ef00b40d30 100644 --- a/plugin/dapp/exchange/executor/exchange.go +++ b/plugin/dapp/exchange/executor/exchange.go @@ -35,7 +35,7 @@ type exchange struct { drivers.DriverBase } -//NewExchange ... +// NewExchange ... func NewExchange() drivers.Driver { t := &exchange{} t.SetChild(t) @@ -48,7 +48,7 @@ func GetName() string { return NewExchange().GetName() } -//GetDriverName ... +// GetDriverName ... func (e *exchange) GetDriverName() string { return driverName } @@ -85,7 +85,7 @@ func (e *exchange) CheckTx(tx *types.Transaction, index int) error { return nil } -//ExecutorOrder Exec 的时候 同时执行 ExecLocal +// ExecutorOrder Exec 的时候 同时执行 ExecLocal func (e *exchange) ExecutorOrder() int64 { return drivers.ExecLocalSameTime } diff --git a/plugin/dapp/exchange/executor/exchange_test.go b/plugin/dapp/exchange/executor/exchange_test.go index c72ea275fc..cc585bcc2f 100644 --- a/plugin/dapp/exchange/executor/exchange_test.go +++ b/plugin/dapp/exchange/executor/exchange_test.go @@ -711,7 +711,7 @@ func CreateRevokeOrder(orderID int64, privKey string) (tx *types.Transaction, er return tx, nil } -//模拟区块中交易得执行过程 +// 模拟区块中交易得执行过程 func Exec_Block(t *testing.T, stateDB db.DB, kvdb db.KVDB, env *execEnv, txs ...*types.Transaction) error { cfg := types.NewChain33Config(et.GetDefaultCfgstring()) cfg.SetTitleOnlyForTest("chain33") diff --git a/plugin/dapp/exchange/executor/exchangedb.go b/plugin/dapp/exchange/executor/exchangedb.go index 922ed4f16c..a115d95cbd 100644 --- a/plugin/dapp/exchange/executor/exchangedb.go +++ b/plugin/dapp/exchange/executor/exchangedb.go @@ -29,7 +29,7 @@ type Action struct { api client.QueueProtocolAPI } -//NewAction ... +// NewAction ... func NewAction(e *exchange, tx *types.Transaction, index int) *Action { hash := tx.Hash() fromaddr := tx.From() @@ -46,19 +46,19 @@ func NewAction(e *exchange, tx *types.Transaction, index int) *Action { } } -//GetIndex get index +// GetIndex get index func (a *Action) GetIndex() int64 { // Add four zeros to match multiple MatchOrder indexes return (a.height*types.MaxTxsPerBlock + int64(a.index)) * 1e4 } -//GetKVSet get kv set +// GetKVSet get kv set func (a *Action) GetKVSet(order *et.Order) (kvset []*types.KeyValue) { kvset = append(kvset, &types.KeyValue{Key: calcOrderKey(order.OrderID), Value: types.Encode(order)}) return kvset } -//OpSwap reverse +// OpSwap reverse func (a *Action) OpSwap(op int32) int32 { if op == et.OpBuy { return et.OpSell @@ -66,7 +66,7 @@ func (a *Action) OpSwap(op int32) int32 { return et.OpBuy } -//CalcActualCost Calculate actual cost +// CalcActualCost Calculate actual cost func CalcActualCost(op int32, amount int64, price, coinPrecision int64) int64 { if op == et.OpBuy { return SafeMul(amount, price, coinPrecision) @@ -74,7 +74,7 @@ func CalcActualCost(op int32, amount int64, price, coinPrecision int64) int64 { return amount } -//CheckPrice price 1<=price<=1e16 +// CheckPrice price 1<=price<=1e16 func CheckPrice(price int64) bool { if price > 1e16 || price < 1 { return false @@ -82,7 +82,7 @@ func CheckPrice(price int64) bool { return true } -//CheckOp ... +// CheckOp ... func CheckOp(op int32) bool { if op == et.OpBuy || op == et.OpSell { return true @@ -90,7 +90,7 @@ func CheckOp(op int32) bool { return false } -//CheckCount ... +// CheckCount ... func CheckCount(count int32) bool { return count <= 20 && count >= 0 } @@ -99,7 +99,7 @@ func Check5Count(count int32) bool { return count <= 50 && count >= 0 } -//CheckAmount 最小交易 1coin +// CheckAmount 最小交易 1coin func CheckAmount(amount, coinPrecision int64) bool { if amount < 1 || amount >= types.MaxCoin*coinPrecision { return false @@ -107,7 +107,7 @@ func CheckAmount(amount, coinPrecision int64) bool { return true } -//CheckDirection ... +// CheckDirection ... func CheckDirection(direction int32) bool { if direction == et.ListASC || direction == et.ListDESC { return true @@ -115,7 +115,7 @@ func CheckDirection(direction int32) bool { return false } -//CheckStatus ... +// CheckStatus ... func CheckStatus(status int32) bool { if status == et.Ordered || status == et.Completed || status == et.Revoked { return true @@ -123,7 +123,7 @@ func CheckStatus(status int32) bool { return false } -//CheckExchangeAsset +// CheckExchangeAsset func CheckExchangeAsset(coinExec string, left, right *et.Asset) bool { if left.Execer == "" || left.Symbol == "" || right.Execer == "" || right.Symbol == "" { return false @@ -134,12 +134,12 @@ func CheckExchangeAsset(coinExec string, left, right *et.Asset) bool { return true } -//CheckDepth 1:价格精度;priceDigits+3:精度为百位 +// CheckDepth 1:价格精度;priceDigits+3:精度为百位 func CheckDepth(depth, priceDigits int32) bool { return depth <= priceDigits+3 && depth >= 1 } -//LimitOrder ... +// LimitOrder ... func (a *Action) LimitOrder(payload *et.LimitOrder, entrustAddr string) (*types.Receipt, error) { leftAsset := payload.GetLeftAsset() rightAsset := payload.GetRightAsset() @@ -188,7 +188,7 @@ func (a *Action) LimitOrder(payload *et.LimitOrder, entrustAddr string) (*types. return nil, fmt.Errorf("unknow op") } -//RevokeOrder ... +// RevokeOrder ... func (a *Action) RevokeOrder(payload *et.RevokeOrder) (*types.Receipt, error) { var logs []*types.ReceiptLog var kvs []*types.KeyValue @@ -265,9 +265,9 @@ func (a *Action) RevokeOrder(payload *et.RevokeOrder) (*types.Receipt, error) { // set the transaction logic method // rules: -//1. The purchase price is higher than the market price, and the price is matched from low to high. -//2. Sell orders are matched at prices lower than market prices. -//3. Match the same prices on a first-in, first-out basis +// 1. The purchase price is higher than the market price, and the price is matched from low to high. +// 2. Sell orders are matched at prices lower than market prices. +// 3. Match the same prices on a first-in, first-out basis func (a *Action) matchLimitOrder(payload *et.LimitOrder, leftAccountDB, rightAccountDB *account.DB, entrustAddr string) (*types.Receipt, error) { var ( logs []*types.ReceiptLog @@ -668,8 +668,8 @@ func findOrderIDListByPrice(localdb dbm.KV, left, right *et.Asset, price int64, return &orderList, nil } -//Direction -//Buying depth is in reverse order by price, from high to low +// Direction +// Buying depth is in reverse order by price, from high to low func Direction(op int32) int32 { if op == et.OpBuy { return et.ListDESC @@ -677,8 +677,8 @@ func Direction(op int32) int32 { return et.ListASC } -//QueryMarketDepth 这里primaryKey当作主键索引来用, -//The first query does not need to fill in the value, pay according to the price from high to low, selling orders according to the price from low to high query +// QueryMarketDepth 这里primaryKey当作主键索引来用, +// The first query does not need to fill in the value, pay according to the price from high to low, selling orders according to the price from low to high query func QueryMarketDepth(localdb dbm.KV, left, right *et.Asset, op int32, primaryKey string, count int32) (*et.MarketDepthList, error) { table := NewMarketDepthTable(localdb) prefix := []byte(fmt.Sprintf("%s:%s:%d", left.GetSymbol(), right.GetSymbol(), op)) @@ -706,7 +706,7 @@ func QueryMarketDepth(localdb dbm.KV, left, right *et.Asset, op int32, primaryKe return &list, nil } -//QueryMarketDepth 查询市场深度(买卖一起返回,不做聚合) +// QueryMarketDepth 查询市场深度(买卖一起返回,不做聚合) func QueryAllMarketDepth(localdb dbm.KV, left, right *et.Asset, count int32) (*et.MarketAllDepth, error) { var list et.MarketAllDepth @@ -856,7 +856,7 @@ func QueryAskDepth(localdb dbm.KV, left, right *et.Asset, count int32, depth int } } -//QueryHistoryOrderList Only the order information is returned +// QueryHistoryOrderList Only the order information is returned func QueryHistoryOrderList(localdb dbm.KV, left, right *et.Asset, primaryKey string, count, direction int32) (types.Message, error) { table := NewHistoryOrderTable(localdb) prefix := []byte(fmt.Sprintf("%s:%s", left.Symbol, right.Symbol)) @@ -901,7 +901,7 @@ HERE: return &orderList, nil } -//QueryOrderList Displays the latest by default +// QueryOrderList Displays the latest by default func QueryOrderList(localdb dbm.KV, addr string, status, count, direction int32, primaryKey string) (types.Message, error) { var table *tab.Table if status == et.Completed || status == et.Revoked { @@ -950,14 +950,14 @@ func queryMarketDepth(marketTable *tab.Table, left, right *et.Asset, op int32, p return row.Data.(*et.MarketDepth), nil } -//SafeMul Safe multiplication of large numbers, prevent overflow +// SafeMul Safe multiplication of large numbers, prevent overflow func SafeMul(x, y, coinPrecision int64) int64 { res := big.NewInt(0).Mul(big.NewInt(x), big.NewInt(y)) res = big.NewInt(0).Div(res, big.NewInt(coinPrecision)) return res.Int64() } -//Calculate the average transaction price +// Calculate the average transaction price func caclAVGPrice(order *et.Order, price int64, amount int64) int64 { x := big.NewInt(0).Mul(big.NewInt(order.AVGPrice), big.NewInt(order.GetLimitOrder().Amount-order.GetBalance())) y := big.NewInt(0).Mul(big.NewInt(price), big.NewInt(amount)) @@ -967,7 +967,7 @@ func caclAVGPrice(order *et.Order, price int64, amount int64) int64 { return avg.Int64() } -//计Calculation fee +// 计Calculation fee func calcMtfFee(cost int64, rate int32) int64 { fee := big.NewInt(0).Mul(big.NewInt(cost), big.NewInt(int64(rate))) fee = big.NewInt(0).Div(fee, big.NewInt(types.DefaultCoinPrecision)) @@ -1093,13 +1093,13 @@ func ParseSymbols(cfg *types.Chain33Config, tradeKey string, height int64) (symb return } func formatInterface(data interface{}) int64 { - switch data.(type) { + switch d := data.(type) { case int64: - return data.(int64) + return d case int32: - return int64(data.(int32)) + return int64(d) case int: - return int64(data.(int)) + return int64(d) default: return 0 } diff --git a/plugin/dapp/exchange/executor/exec_local.go b/plugin/dapp/exchange/executor/exec_local.go index b6d7593dd5..3497be6d99 100644 --- a/plugin/dapp/exchange/executor/exec_local.go +++ b/plugin/dapp/exchange/executor/exec_local.go @@ -266,7 +266,7 @@ func (e *exchange) updateMatchOrders(marketTable, orderTable, historyTable *tabl return nil } -//OpSwap ... +// OpSwap ... func OpSwap(op int32) int32 { if op == ety.OpBuy { return ety.OpSell diff --git a/plugin/dapp/exchange/executor/query.go b/plugin/dapp/exchange/executor/query.go index 9156b4f5a6..5ecbc7f861 100644 --- a/plugin/dapp/exchange/executor/query.go +++ b/plugin/dapp/exchange/executor/query.go @@ -7,7 +7,7 @@ import ( et "github.com/33cn/plugin/plugin/dapp/exchange/types" ) -//查询市场深度 +// 查询市场深度 func (e *exchange) Query_QueryMarketDepth(in *et.QueryMarketDepth) (types.Message, error) { if !CheckCount(in.Count) { return nil, et.ErrCount @@ -22,7 +22,7 @@ func (e *exchange) Query_QueryMarketDepth(in *et.QueryMarketDepth) (types.Messag return QueryMarketDepth(e.GetLocalDB(), in.LeftAsset, in.RightAsset, in.Op, in.PrimaryKey, in.Count) } -//查询市场深度(分档位) +// 查询市场深度(分档位) func (e *exchange) Query_QueryDepth(in *et.QueryMarketDepth) (types.Message, error) { if in.Count == 0 { in.Count = et.Count @@ -51,7 +51,7 @@ func (e *exchange) Query_QueryDepth(in *et.QueryMarketDepth) (types.Message, err return QueryAllDept(e.GetLocalDB(), in.LeftAsset, in.RightAsset, in.Op, in.Count, int64(1e10/math.Pow10(int(priceDigits-(in.Depth-1)+2)))) } -//查询已经完成得订单 +// 查询已经完成得订单 func (e *exchange) Query_QueryHistoryOrderList(in *et.QueryHistoryOrderList) (types.Message, error) { if !CheckExchangeAsset(e.GetAPI().GetConfig().GetCoinExec(), in.LeftAsset, in.RightAsset) { return nil, et.ErrAsset @@ -66,7 +66,7 @@ func (e *exchange) Query_QueryHistoryOrderList(in *et.QueryHistoryOrderList) (ty return QueryHistoryOrderList(e.GetLocalDB(), in.LeftAsset, in.RightAsset, in.PrimaryKey, in.Count, in.Direction) } -//根据orderID查询订单信息 +// 根据orderID查询订单信息 func (e *exchange) Query_QueryOrder(in *et.QueryOrder) (types.Message, error) { if in.OrderID == 0 { return nil, et.ErrOrderID @@ -74,7 +74,7 @@ func (e *exchange) Query_QueryOrder(in *et.QueryOrder) (types.Message, error) { return findOrderByOrderID(e.GetStateDB(), e.GetLocalDB(), in.OrderID) } -//根据订单状态,查询订单信息(这里面包含所有交易对) +// 根据订单状态,查询订单信息(这里面包含所有交易对) func (e *exchange) Query_QueryOrderList(in *et.QueryOrderList) (types.Message, error) { if !CheckStatus(in.Status) { return nil, et.ErrStatus diff --git a/plugin/dapp/exchange/executor/tables.go b/plugin/dapp/exchange/executor/tables.go index bb24e9c6bf..6d4c3a9eed 100644 --- a/plugin/dapp/exchange/executor/tables.go +++ b/plugin/dapp/exchange/executor/tables.go @@ -24,7 +24,7 @@ const ( KeyPrefixLocalDB = "LODB-exchange" ) -//状态数据库中存储具体挂单信息 +// 状态数据库中存储具体挂单信息 func calcOrderKey(orderID int64) []byte { key := fmt.Sprintf("%s"+"orderID:%022d", KeyPrefixStateDB, orderID) return []byte(key) @@ -37,7 +37,7 @@ var opt_exchange_depth = &table.Option{ Index: nil, } -//重新设计表,list查询全部在订单信息localdb查询中 +// 重新设计表,list查询全部在订单信息localdb查询中 var opt_exchange_order = &table.Option{ Prefix: KeyPrefixLocalDB, Name: "order", @@ -52,7 +52,7 @@ var opt_exchange_history = &table.Option{ Index: []string{"name", "addr_status"}, } -//NewMarketDepthTable 新建表 +// NewMarketDepthTable 新建表 func NewMarketDepthTable(kvdb db.KV) *table.Table { rowmeta := NewMarketDepthRow() table, err := table.NewTable(rowmeta, kvdb, opt_exchange_depth) @@ -62,7 +62,7 @@ func NewMarketDepthTable(kvdb db.KV) *table.Table { return table } -//NewMarketOrderTable ... +// NewMarketOrderTable ... func NewMarketOrderTable(kvdb db.KV) *table.Table { rowmeta := NewOrderRow() table, err := table.NewTable(rowmeta, kvdb, opt_exchange_order) @@ -72,7 +72,7 @@ func NewMarketOrderTable(kvdb db.KV) *table.Table { return table } -//NewHistoryOrderTable ... +// NewHistoryOrderTable ... func NewHistoryOrderTable(kvdb db.KV) *table.Table { rowmeta := NewHistoryOrderRow() table, err := table.NewTable(rowmeta, kvdb, opt_exchange_history) @@ -82,22 +82,22 @@ func NewHistoryOrderTable(kvdb db.KV) *table.Table { return table } -//OrderRow table meta 结构 +// OrderRow table meta 结构 type OrderRow struct { *ety.Order } -//NewOrderRow 新建一个meta 结构 +// NewOrderRow 新建一个meta 结构 func NewOrderRow() *OrderRow { return &OrderRow{Order: &ety.Order{}} } -//CreateRow ... +// CreateRow ... func (r *OrderRow) CreateRow() *table.Row { return &table.Row{Data: &ety.Order{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *OrderRow) SetPayload(data types.Message) error { if txdata, ok := data.(*ety.Order); ok { r.Order = txdata @@ -106,7 +106,7 @@ func (r *OrderRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *OrderRow) Get(key string) ([]byte, error) { if key == "orderID" { return []byte(fmt.Sprintf("%022d", r.OrderID)), nil @@ -118,22 +118,22 @@ func (r *OrderRow) Get(key string) ([]byte, error) { return nil, types.ErrNotFound } -//HistoryOrderRow table meta 结构 +// HistoryOrderRow table meta 结构 type HistoryOrderRow struct { *ety.Order } -//NewHistoryOrderRow ... +// NewHistoryOrderRow ... func NewHistoryOrderRow() *HistoryOrderRow { return &HistoryOrderRow{Order: &ety.Order{Value: &ety.Order_LimitOrder{LimitOrder: &ety.LimitOrder{}}}} } -//CreateRow ... +// CreateRow ... func (m *HistoryOrderRow) CreateRow() *table.Row { return &table.Row{Data: &ety.Order{Value: &ety.Order_LimitOrder{LimitOrder: &ety.LimitOrder{}}}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (m *HistoryOrderRow) SetPayload(data types.Message) error { if txdata, ok := data.(*ety.Order); ok { m.Order = txdata @@ -142,7 +142,7 @@ func (m *HistoryOrderRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (m *HistoryOrderRow) Get(key string) ([]byte, error) { if key == "index" { return []byte(fmt.Sprintf("%022d", m.Index)), nil @@ -154,22 +154,22 @@ func (m *HistoryOrderRow) Get(key string) ([]byte, error) { return nil, types.ErrNotFound } -//MarketDepthRow table meta 结构 +// MarketDepthRow table meta 结构 type MarketDepthRow struct { *ety.MarketDepth } -//NewMarketDepthRow 新建一个meta 结构 +// NewMarketDepthRow 新建一个meta 结构 func NewMarketDepthRow() *MarketDepthRow { return &MarketDepthRow{MarketDepth: &ety.MarketDepth{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存eventid) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存eventid) func (m *MarketDepthRow) CreateRow() *table.Row { return &table.Row{Data: &ety.MarketDepth{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (m *MarketDepthRow) SetPayload(data types.Message) error { if txdata, ok := data.(*ety.MarketDepth); ok { m.MarketDepth = txdata @@ -178,7 +178,7 @@ func (m *MarketDepthRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (m *MarketDepthRow) Get(key string) ([]byte, error) { if key == "price" { return []byte(fmt.Sprintf("%s:%s:%d:%016d", m.LeftAsset.GetSymbol(), m.RightAsset.GetSymbol(), m.Op, m.Price)), nil diff --git a/plugin/dapp/exchange/test/client.go b/plugin/dapp/exchange/test/client.go index 451c3af396..a93b569c2b 100644 --- a/plugin/dapp/exchange/test/client.go +++ b/plugin/dapp/exchange/test/client.go @@ -5,7 +5,7 @@ import ( "github.com/golang/protobuf/proto" ) -//Cli interface +// Cli interface type Cli interface { Send(tx *types.Transaction, hexKey string) ([]*types.ReceiptLog, error) Query(fn string, msg proto.Message) ([]byte, error) diff --git a/plugin/dapp/exchange/test/cmd/main.go b/plugin/dapp/exchange/test/cmd/main.go index 7b34b8a88b..1f933ec1ff 100644 --- a/plugin/dapp/exchange/test/cmd/main.go +++ b/plugin/dapp/exchange/test/cmd/main.go @@ -8,7 +8,7 @@ import ( et "github.com/33cn/plugin/plugin/dapp/exchange/types" ) -//setting ... +// setting ... var ( cli *test.GRPCCli PrivKeyA = "0x6da92a632ab7deb67d38c0f6560bcfed28167998f6496db64c258d5e8393a81b" // 1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4 diff --git a/plugin/dapp/exchange/test/exchange_test.go b/plugin/dapp/exchange/test/exchange_test.go index 1e42c273ba..c8b3d6c184 100644 --- a/plugin/dapp/exchange/test/exchange_test.go +++ b/plugin/dapp/exchange/test/exchange_test.go @@ -85,10 +85,10 @@ func TestSample0(t *testing.T) { assert.Nil(t, depth) } -//买卖单价格相同,测试正常撮合流程,查询功能是否可用 -//1.先挂数量是10的买单。 -//2.然后再挂数量是5的吃单 -//3.最后撤销未成交部分的买单 +// 买卖单价格相同,测试正常撮合流程,查询功能是否可用 +// 1.先挂数量是10的买单。 +// 2.然后再挂数量是5的吃单 +// 3.最后撤销未成交部分的买单 func TestCase1(t *testing.T) { //先挂数量是10的买单 req := &et.LimitOrder{LeftAsset: leftAsset, RightAsset: rightAsset, Price: 4, Amount: 10 * types.DefaultCoinPrecision, Op: et.OpBuy} diff --git a/plugin/dapp/exchange/test/exec_cli.go b/plugin/dapp/exchange/test/exec_cli.go index c45d7d5363..cd837b3f2e 100644 --- a/plugin/dapp/exchange/test/exec_cli.go +++ b/plugin/dapp/exchange/test/exec_cli.go @@ -21,7 +21,7 @@ import ( et "github.com/33cn/plugin/plugin/dapp/exchange/types" ) -//ExecCli ... +// ExecCli ... type ExecCli struct { ldb db.KVDB sdb db.DB @@ -44,7 +44,7 @@ type ExecCli struct { accF1 *account.DB } -//Nodes ... +// Nodes ... var ( Nodes = []string{ "1KSBd17H7ZK8iT37aJztFB22XGwsPTdwE4", @@ -55,7 +55,7 @@ var ( } ) -//NewExecCli ... +// NewExecCli ... func NewExecCli() *ExecCli { dir, sdb, ldb := util.CreateTestDB() log.Println(dir) @@ -149,7 +149,7 @@ func NewExecCli() *ExecCli { } } -//Send ... +// Send ... func (c *ExecCli) Send(tx *types.Transaction, hexKey string) ([]*types.ReceiptLog, error) { var err error tx, err = types.FormatTx(c.cfg, et.ExchangeX, tx) @@ -200,7 +200,7 @@ func (c *ExecCli) Send(tx *types.Transaction, hexKey string) ([]*types.ReceiptLo return receipt.Logs, nil } -//Query ... +// Query ... func (c *ExecCli) Query(fn string, msg proto.Message) ([]byte, error) { api, _ := client.New(c.q.Client(), nil) exec := executor.NewExchange() @@ -236,7 +236,7 @@ func signTx(tx *types.Transaction, hexPrivKey string) (*types.Transaction, error return tx, nil } -//GetExecAccount ... +// GetExecAccount ... func (c *ExecCli) GetExecAccount(addr string, exec string, symbol string) (*types.Account, error) { //mavl-{coins}-{bty}-exec-{26htvcBNSEA7fZhAdLJphDwQRQJaHpyHTp}:{1JmFaA6unrCFYEWPGRi7uuXY1KthTJxJEP} //mavl-{token}-{ccny}-exec-{26htvcBNSEA7fZhAdLJphDwQRQJaHpyHTp}:{1JmFaA6unrCFYEWPGRi7uuXY1KthTJxJEP} diff --git a/plugin/dapp/exchange/test/grpc_cli.go b/plugin/dapp/exchange/test/grpc_cli.go index 86da03a64a..dc654892fd 100644 --- a/plugin/dapp/exchange/test/grpc_cli.go +++ b/plugin/dapp/exchange/test/grpc_cli.go @@ -16,12 +16,12 @@ import ( "google.golang.org/grpc" ) -//GRPCCli ... +// GRPCCli ... type GRPCCli struct { client types.Chain33Client } -//NewGRPCCli ... +// NewGRPCCli ... func NewGRPCCli(grpcAddr string) *GRPCCli { conn, err := grpc.Dial(grpcAddr, grpc.WithInsecure()) if err != nil { @@ -36,7 +36,7 @@ func NewGRPCCli(grpcAddr string) *GRPCCli { } } -//Send ... +// Send ... func (c *GRPCCli) Send(tx *types.Transaction, hexKey string) ([]*types.ReceiptLog, error) { txHash, logs, err := c.sendAndWaitReceipt(tx, hexKey) if txHash != nil { @@ -53,7 +53,7 @@ func (c *GRPCCli) Send(tx *types.Transaction, hexKey string) ([]*types.ReceiptLo return logs, nil } -//Query ... +// Query ... func (c *GRPCCli) Query(fn string, msg proto.Message) ([]byte, error) { ss := strings.Split(fn, ".") var in types.ChainExecutor @@ -76,7 +76,7 @@ func (c *GRPCCli) Query(fn string, msg proto.Message) ([]byte, error) { return r.Msg, nil } -//GetExecAccount ... +// GetExecAccount ... func (c *GRPCCli) GetExecAccount(addr string, exec string, symbol string) (*types.Account, error) { if exec == "coins" { // bty @@ -136,7 +136,7 @@ func (c *GRPCCli) sendAndWaitReceipt(tx *types.Transaction, hexKey string) (txHa return r.Msg, d.Receipt.Logs, nil } -//SendTx ... +// SendTx ... func (c *GRPCCli) SendTx(tx *types.Transaction, hexKey string) (reply *types.Reply, err error) { cfg := types.NewChain33Config(et.GetDefaultCfgstring()) cfg.SetTitleOnlyForTest("chain33") diff --git a/plugin/dapp/exchange/types/exchange.go b/plugin/dapp/exchange/types/exchange.go index 4a253e48e9..389b644063 100644 --- a/plugin/dapp/exchange/types/exchange.go +++ b/plugin/dapp/exchange/types/exchange.go @@ -52,14 +52,14 @@ const ( OpSell ) -//order status +// order status const ( Ordered = iota Completed Revoked ) -//const +// const const ( ListDESC = int32(0) ListASC = int32(1) @@ -177,12 +177,12 @@ func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(ExchangeX, NewType(cfg)) } -//ExchangeType ... +// ExchangeType ... type ExchangeType struct { types.ExecTypeBase } -//NewType ... +// NewType ... func NewType(cfg *types.Chain33Config) *ExchangeType { c := &ExchangeType{} c.SetChild(c) diff --git a/plugin/dapp/exchange/types/exchange.pb.go b/plugin/dapp/exchange/types/exchange.pb.go index 3262858a1b..08c9b33d5f 100644 --- a/plugin/dapp/exchange/types/exchange.pb.go +++ b/plugin/dapp/exchange/types/exchange.pb.go @@ -205,7 +205,7 @@ func (*ExchangeAction_EntrustOrder) isExchangeAction_Value() {} func (*ExchangeAction_EntrustRevokeOrder) isExchangeAction_Value() {} -//限价订单 +// 限价订单 type LimitOrder struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -290,7 +290,7 @@ func (x *LimitOrder) GetOp() int32 { return 0 } -//市价委托 +// 市价委托 type MarketOrder struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -423,7 +423,7 @@ func (x *ExchangeBind) GetEntrustAddress() string { return "" } -//委托限价订单 +// 委托限价订单 type EntrustOrder struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -517,7 +517,7 @@ func (x *EntrustOrder) GetAddr() string { return "" } -//委托撤回订单 +// 委托撤回订单 type EntrustRevokeOrder struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -575,7 +575,7 @@ func (x *EntrustRevokeOrder) GetAddr() string { return "" } -//撤回订单 +// 撤回订单 type RevokeOrder struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -624,7 +624,7 @@ func (x *RevokeOrder) GetOrderID() int64 { return 0 } -//资产类型 +// 资产类型 type Asset struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -680,7 +680,7 @@ func (x *Asset) GetSymbol() string { return "" } -//订单信息 +// 订单信息 type Order struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -904,7 +904,7 @@ func (*Order_LimitOrder) isOrder_Value() {} func (*Order_MarketOrder) isOrder_Value() {} -//查询接口 +// 查询接口 type QueryMarketDepth struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -998,7 +998,7 @@ func (x *QueryMarketDepth) GetDepth() int32 { return 0 } -//市场深度 +// 市场深度 type MarketDepth struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1083,7 +1083,7 @@ func (x *MarketDepth) GetOp() int32 { return 0 } -//查询接口返回的市场深度列表 +// 查询接口返回的市场深度列表 type MarketDepthList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1139,7 +1139,7 @@ func (x *MarketDepthList) GetPrimaryKey() string { return "" } -//查询接口返回的市场买卖深度 +// 查询接口返回的市场买卖深度 type MarketAllDepth struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1197,7 +1197,7 @@ func (x *MarketAllDepth) GetAsks() []*MarketDepth { return nil } -//查询最新得成交信息,外部接口 +// 查询最新得成交信息,外部接口 type QueryHistoryOrderList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1282,7 +1282,7 @@ func (x *QueryHistoryOrderList) GetDirection() int32 { return 0 } -//根据orderID去查询订单信息 +// 根据orderID去查询订单信息 type QueryOrder struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1330,7 +1330,7 @@ func (x *QueryOrder) GetOrderID() int64 { return 0 } -//根据地址,状态查询用户自己的挂单信息 +// 根据地址,状态查询用户自己的挂单信息 type QueryOrderList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1415,7 +1415,7 @@ func (x *QueryOrderList) GetDirection() int32 { return 0 } -//订单列表 +// 订单列表 type OrderList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/exchange/types/exchangecfg.go b/plugin/dapp/exchange/types/exchangecfg.go index d5367bf65d..333325ea47 100644 --- a/plugin/dapp/exchange/types/exchangecfg.go +++ b/plugin/dapp/exchange/types/exchangecfg.go @@ -550,7 +550,7 @@ useBalance=false jdkPath="../../../../build/j2sdk-image" ` -//GetDefaultCfgstring ... +// GetDefaultCfgstring ... func GetDefaultCfgstring() string { return cfgstring //return defaultCfgstring diff --git a/plugin/dapp/game/executor/game.go b/plugin/dapp/game/executor/game.go index 879b85f3d2..1ca158a2bc 100644 --- a/plugin/dapp/game/executor/game.go +++ b/plugin/dapp/game/executor/game.go @@ -23,7 +23,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Game{})) diff --git a/plugin/dapp/game/executor/gamedb.go b/plugin/dapp/game/executor/gamedb.go index 13f3b62d56..74d694de03 100644 --- a/plugin/dapp/game/executor/gamedb.go +++ b/plugin/dapp/game/executor/gamedb.go @@ -112,12 +112,12 @@ func (action *Action) GetReceiptLog(game *gt.Game) *types.ReceiptLog { return log } -//GetIndex get index +// GetIndex get index func (action *Action) GetIndex(game *gt.Game) int64 { return action.height*types.MaxTxsPerBlock + int64(action.index) } -//GetKVSet get kv set +// GetKVSet get kv set func (action *Action) GetKVSet(game *gt.Game) (kvset []*types.KeyValue) { value := types.Encode(game) kvset = append(kvset, &types.KeyValue{Key: Key(game.GameId), Value: value}) @@ -497,7 +497,7 @@ func (action *Action) checkGameIsTimeOut(game *gt.Game) bool { return action.blocktime > (game.GetMatchTime() + DurTime) } -//根据传入密钥,揭晓游戏结果 +// 根据传入密钥,揭晓游戏结果 func (action *Action) checkGameResult(game *gt.Game, close *gt.GameClose) (int32, int32) { //如果超时,直接走超时开奖逻辑 if action.checkGameIsTimeOut(game) { diff --git a/plugin/dapp/game/types/const.go b/plugin/dapp/game/types/const.go index d3e344ed7c..2acbf77d10 100644 --- a/plugin/dapp/game/types/const.go +++ b/plugin/dapp/game/types/const.go @@ -4,7 +4,7 @@ package types -//game action ty +// game action ty const ( GameActionCreate = iota + 1 GameActionMatch @@ -18,9 +18,9 @@ const ( TyLogCloseGame = 714 ) -//包的名字可以通过配置文件来配置 -//建议用github的组织名称,或者用户名字开头, 再加上自己的插件的名字 -//如果发生重名,可以通过配置文件修改这些名字 +// 包的名字可以通过配置文件来配置 +// 建议用github的组织名称,或者用户名字开头, 再加上自己的插件的名字 +// 如果发生重名,可以通过配置文件修改这些名字 var ( GameX = "game" ExecerGame = []byte(GameX) diff --git a/plugin/dapp/game/types/types.go b/plugin/dapp/game/types/types.go index 797170c665..87788ae6e0 100644 --- a/plugin/dapp/game/types/types.go +++ b/plugin/dapp/game/types/types.go @@ -22,20 +22,20 @@ func init() { types.RegExec(GameX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(GameX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(GameX, NewType(cfg)) } -//getRealExecName -//如果paraName == "", 那么自动用 types.ExecName("game") -//如果设置了paraName , 那么强制用paraName -//也就是说,我们可以构造其他平行链的交易 +// getRealExecName +// 如果paraName == "", 那么自动用 types.ExecName("game") +// 如果设置了paraName , 那么强制用paraName +// 也就是说,我们可以构造其他平行链的交易 func getRealExecName(cfg *types.Chain33Config, paraName string) string { return cfg.ExecName(paraName + GameX) } diff --git a/plugin/dapp/guess/commands/game.go b/plugin/dapp/guess/commands/game.go index 2814dee032..b7ffbf49e8 100644 --- a/plugin/dapp/guess/commands/game.go +++ b/plugin/dapp/guess/commands/game.go @@ -15,7 +15,7 @@ import ( "github.com/spf13/cobra" ) -//GuessCmd Guess合约命令行 +// GuessCmd Guess合约命令行 func GuessCmd() *cobra.Command { cmd := &cobra.Command{ Use: "guess", @@ -35,7 +35,7 @@ func GuessCmd() *cobra.Command { return cmd } -//GuessStartRawTxCmd 构造Guess合约的start原始交易(未签名)的命令行 +// GuessStartRawTxCmd 构造Guess合约的start原始交易(未签名)的命令行 func GuessStartRawTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "start", @@ -92,7 +92,7 @@ func guessStart(cmd *cobra.Command, args []string) { } -//GuessBetRawTxCmd 构造Guess合约的bet原始交易(未签名)的命令行 +// GuessBetRawTxCmd 构造Guess合约的bet原始交易(未签名)的命令行 func GuessBetRawTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "bet", @@ -131,7 +131,7 @@ func guessBet(cmd *cobra.Command, args []string) { ctx.RunWithoutMarshal() } -//GuessStopBetRawTxCmd 构造Guess合约的停止下注(stopBet)原始交易(未签名)的命令行 +// GuessStopBetRawTxCmd 构造Guess合约的停止下注(stopBet)原始交易(未签名)的命令行 func GuessStopBetRawTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "stop", @@ -164,7 +164,7 @@ func guessStopBet(cmd *cobra.Command, args []string) { ctx.RunWithoutMarshal() } -//GuessAbortRawTxCmd 构造Guess合约的撤销(Abort)原始交易(未签名)的命令行 +// GuessAbortRawTxCmd 构造Guess合约的撤销(Abort)原始交易(未签名)的命令行 func GuessAbortRawTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "abort", @@ -197,7 +197,7 @@ func guessAbort(cmd *cobra.Command, args []string) { ctx.RunWithoutMarshal() } -//GuessPublishRawTxCmd 构造Guess合约的发布结果(Publish)原始交易(未签名)的命令行 +// GuessPublishRawTxCmd 构造Guess合约的发布结果(Publish)原始交易(未签名)的命令行 func GuessPublishRawTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "publish", @@ -234,7 +234,7 @@ func guessPublish(cmd *cobra.Command, args []string) { ctx.RunWithoutMarshal() } -//GuessQueryRawTxCmd 构造Guess合约的查询(Query)命令行 +// GuessQueryRawTxCmd 构造Guess合约的查询(Query)命令行 func GuessQueryRawTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "query", diff --git a/plugin/dapp/guess/executor/exec.go b/plugin/dapp/guess/executor/exec.go index 1ee78ab035..f9d3fb8b8e 100644 --- a/plugin/dapp/guess/executor/exec.go +++ b/plugin/dapp/guess/executor/exec.go @@ -9,31 +9,31 @@ import ( gty "github.com/33cn/plugin/plugin/dapp/guess/types" ) -//Exec_Start Guess执行器创建游戏 +// Exec_Start Guess执行器创建游戏 func (c *Guess) Exec_Start(payload *gty.GuessGameStart, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(c, tx, index) return action.GameStart(payload) } -//Exec_Bet Guess执行器参与游戏 +// Exec_Bet Guess执行器参与游戏 func (c *Guess) Exec_Bet(payload *gty.GuessGameBet, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(c, tx, index) return action.GameBet(payload) } -//Exec_StopBet Guess执行器停止游戏下注 +// Exec_StopBet Guess执行器停止游戏下注 func (c *Guess) Exec_StopBet(payload *gty.GuessGameStopBet, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(c, tx, index) return action.GameStopBet(payload) } -//Exec_Publish Guess执行器公布游戏结果 +// Exec_Publish Guess执行器公布游戏结果 func (c *Guess) Exec_Publish(payload *gty.GuessGamePublish, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(c, tx, index) return action.GamePublish(payload) } -//Exec_Abort Guess执行器撤销未结束游戏 +// Exec_Abort Guess执行器撤销未结束游戏 func (c *Guess) Exec_Abort(payload *gty.GuessGameAbort, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(c, tx, index) return action.GameAbort(payload) diff --git a/plugin/dapp/guess/executor/exec_del_local.go b/plugin/dapp/guess/executor/exec_del_local.go index 8ef9441e41..04ca30c062 100644 --- a/plugin/dapp/guess/executor/exec_del_local.go +++ b/plugin/dapp/guess/executor/exec_del_local.go @@ -139,22 +139,22 @@ func (g *Guess) execDelLocal(receipt *types.ReceiptData) (*types.LocalDBSet, err return dbSet, nil } -//ExecDelLocal_Start Guess执行器Start交易撤销 +// ExecDelLocal_Start Guess执行器Start交易撤销 func (g *Guess) ExecDelLocal_Start(payload *gty.GuessGameStart, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return g.execLocal(receiptData) } -//ExecDelLocal_Bet Guess执行器Bet交易撤销 +// ExecDelLocal_Bet Guess执行器Bet交易撤销 func (g *Guess) ExecDelLocal_Bet(payload *gty.GuessGameBet, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return g.execLocal(receiptData) } -//ExecDelLocal_Publish Guess执行器Publish交易撤销 +// ExecDelLocal_Publish Guess执行器Publish交易撤销 func (g *Guess) ExecDelLocal_Publish(payload *gty.GuessGamePublish, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return g.execLocal(receiptData) } -//ExecDelLocal_Abort Guess执行器Abort交易撤销 +// ExecDelLocal_Abort Guess执行器Abort交易撤销 func (g *Guess) ExecDelLocal_Abort(payload *gty.GuessGameAbort, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return g.execLocal(receiptData) } diff --git a/plugin/dapp/guess/executor/exec_local.go b/plugin/dapp/guess/executor/exec_local.go index cc750749f0..40966ab2d4 100644 --- a/plugin/dapp/guess/executor/exec_local.go +++ b/plugin/dapp/guess/executor/exec_local.go @@ -109,27 +109,27 @@ func (g *Guess) execLocal(receipt *types.ReceiptData) (*types.LocalDBSet, error) return dbSet, nil } -//ExecLocal_Start method +// ExecLocal_Start method func (g *Guess) ExecLocal_Start(payload *gty.GuessGameStart, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return g.execLocal(receiptData) } -//ExecLocal_Bet method +// ExecLocal_Bet method func (g *Guess) ExecLocal_Bet(payload *gty.GuessGameBet, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return g.execLocal(receiptData) } -//ExecLocal_StopBet method +// ExecLocal_StopBet method func (g *Guess) ExecLocal_StopBet(payload *gty.GuessGameStopBet, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return g.execLocal(receiptData) } -//ExecLocal_Publish method +// ExecLocal_Publish method func (g *Guess) ExecLocal_Publish(payload *gty.GuessGamePublish, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return g.execLocal(receiptData) } -//ExecLocal_Abort method +// ExecLocal_Abort method func (g *Guess) ExecLocal_Abort(payload *gty.GuessGameAbort, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return g.execLocal(receiptData) } diff --git a/plugin/dapp/guess/executor/guess.go b/plugin/dapp/guess/executor/guess.go index 2a4d809215..e88612297f 100644 --- a/plugin/dapp/guess/executor/guess.go +++ b/plugin/dapp/guess/executor/guess.go @@ -26,13 +26,13 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Guess{})) } -//Guess 执行器,用于竞猜合约的具体执行 +// Guess 执行器,用于竞猜合约的具体执行 type Guess struct { drivers.DriverBase } @@ -44,17 +44,17 @@ func newGuessGame() drivers.Driver { return t } -//GetName 获取Guess执行器的名称 +// GetName 获取Guess执行器的名称 func GetName() string { return newGuessGame().GetName() } -//ExecutorOrder Exec 的时候 同时执行 ExecLocal +// ExecutorOrder Exec 的时候 同时执行 ExecLocal func (g *Guess) ExecutorOrder() int64 { return drivers.ExecLocalSameTime } -//GetDriverName 获取Guess执行器的名称 +// GetDriverName 获取Guess执行器的名称 func (g *Guess) GetDriverName() string { return gty.GuessX } diff --git a/plugin/dapp/guess/executor/guessdb.go b/plugin/dapp/guess/executor/guessdb.go index 79f05c8240..ca20c1724b 100644 --- a/plugin/dapp/guess/executor/guessdb.go +++ b/plugin/dapp/guess/executor/guessdb.go @@ -45,7 +45,7 @@ const ( MaxExpireHeight = 1000000 ) -//Action 具体动作执行 +// Action 具体动作执行 type Action struct { coinsAccount *account.DB db dbm.KV @@ -59,7 +59,7 @@ type Action struct { mainHeight int64 } -//NewAction 生成Action对象 +// NewAction 生成Action对象 func NewAction(guess *Guess, tx *types.Transaction, index int) *Action { hash := tx.Hash() fromAddr := tx.From() @@ -78,7 +78,7 @@ func NewAction(guess *Guess, tx *types.Transaction, index int) *Action { } } -//CheckExecAccountBalance 检查地址在Guess合约中的余额是否足够 +// CheckExecAccountBalance 检查地址在Guess合约中的余额是否足够 func (action *Action) CheckExecAccountBalance(fromAddr string, ToFrozen, ToActive int64) bool { acc := action.coinsAccount.LoadExecAccount(fromAddr, action.execaddr) if acc.GetBalance() >= ToFrozen && acc.GetFrozen() >= ToActive { @@ -87,7 +87,7 @@ func (action *Action) CheckExecAccountBalance(fromAddr string, ToFrozen, ToActiv return false } -//Key State数据库中存储记录的Key值格式转换 +// Key State数据库中存储记录的Key值格式转换 func Key(id string) (key []byte) { //key = append(key, []byte("mavl-"+types.ExecName(pkt.GuessX)+"-")...) key = append(key, []byte("mavl-"+gty.GuessX+"-")...) @@ -95,7 +95,7 @@ func Key(id string) (key []byte) { return key } -//queryGameInfos 根据游戏id列表查询多个游戏详情信息 +// queryGameInfos 根据游戏id列表查询多个游戏详情信息 func queryGameInfos(kvdb db.KVDB, infos *gty.QueryGuessGameInfos) (types.Message, error) { var games []*gty.GuessGame gameTable := gty.NewGuessGameTable(kvdb) @@ -113,7 +113,7 @@ func queryGameInfos(kvdb db.KVDB, infos *gty.QueryGuessGameInfos) (types.Message return >y.ReplyGuessGameInfos{Games: games}, nil } -//queryGameInfo 根据gameid查询game信息 +// queryGameInfo 根据gameid查询game信息 func queryGameInfo(kvdb db.KVDB, gameID []byte) (*gty.GuessGame, error) { gameTable := gty.NewGuessGameTable(kvdb) query := gameTable.GetQuery(kvdb) @@ -127,7 +127,7 @@ func queryGameInfo(kvdb db.KVDB, gameID []byte) (*gty.GuessGame, error) { return game, nil } -//queryUserTableData 查询user表数据 +// queryUserTableData 查询user表数据 func queryUserTableData(query *table.Query, indexName string, prefix, primaryKey []byte) (types.Message, error) { rows, err := query.ListIndex(indexName, prefix, primaryKey, DefaultCount, 0) if err != nil { @@ -152,7 +152,7 @@ func queryUserTableData(query *table.Query, indexName string, prefix, primaryKey return >y.GuessGameRecords{Records: records, PrimaryKey: primary}, nil } -//queryGameTableData 查询game表数据 +// queryGameTableData 查询game表数据 func queryGameTableData(query *table.Query, indexName string, prefix, primaryKey []byte) (types.Message, error) { rows, err := query.ListIndex(indexName, prefix, primaryKey, DefaultCount, 0) if err != nil { @@ -177,7 +177,7 @@ func queryGameTableData(query *table.Query, indexName string, prefix, primaryKey return >y.GuessGameRecords{Records: records, PrimaryKey: primary}, nil } -//queryJoinTableData 查询join表数据 +// queryJoinTableData 查询join表数据 func queryJoinTableData(talbeJoin *table.JoinTable, indexName string, prefix, primaryKey []byte) (types.Message, error) { rows, err := talbeJoin.ListIndex(indexName, prefix, primaryKey, DefaultCount, 0) if err != nil { @@ -216,7 +216,7 @@ func (action *Action) getIndex() int64 { return action.height*types.MaxTxsPerBlock + int64(action.index) } -//getReceiptLog 根据游戏信息生成收据记录 +// getReceiptLog 根据游戏信息生成收据记录 func (action *Action) getReceiptLog(game *gty.GuessGame, statusChange bool, bet *gty.GuessGameBet) *types.ReceiptLog { log := &types.ReceiptLog{} r := >y.ReceiptGuessGame{} @@ -297,7 +297,7 @@ func (action *Action) newGame(gameID string, start *gty.GuessGameStart) *gty.Gue return game } -//GameStart 创建游戏动作执行 +// GameStart 创建游戏动作执行 func (action *Action) GameStart(start *gty.GuessGameStart) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -369,7 +369,7 @@ func (action *Action) GameStart(start *gty.GuessGameStart) (*types.Receipt, erro return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//GameBet 参与游戏动作执行 +// GameBet 参与游戏动作执行 func (action *Action) GameBet(pbBet *gty.GuessGameBet) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -463,7 +463,7 @@ func (action *Action) GameBet(pbBet *gty.GuessGameBet) (*types.Receipt, error) { return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//GameStopBet 停止游戏下注动作执行 +// GameStopBet 停止游戏下注动作执行 func (action *Action) GameStopBet(pbBet *gty.GuessGameStopBet) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -501,7 +501,7 @@ func (action *Action) GameStopBet(pbBet *gty.GuessGameStopBet) (*types.Receipt, return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//addGuessBet 向游戏结构中加入下注信息 +// addGuessBet 向游戏结构中加入下注信息 func (action *Action) addGuessBet(game *gty.GuessGame, pbBet *gty.GuessGameBet) { bet := >y.GuessBet{Option: pbBet.GetOption(), BetsNumber: pbBet.BetsNum, Index: action.getIndex()} player := >y.GuessPlayer{Addr: action.fromaddr, Bet: bet} @@ -523,7 +523,7 @@ func (action *Action) addGuessBet(game *gty.GuessGame, pbBet *gty.GuessGameBet) game.BetsNumber += pbBet.GetBetsNum() } -//GamePublish 公布竞猜游戏结果动作执行 +// GamePublish 公布竞猜游戏结果动作执行 func (action *Action) GamePublish(publish *gty.GuessGamePublish) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -677,7 +677,7 @@ func (action *Action) GamePublish(publish *gty.GuessGamePublish) (*types.Receipt return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//GameAbort 撤销游戏动作执行 +// GameAbort 撤销游戏动作执行 func (action *Action) GameAbort(pbend *gty.GuessGameAbort) (*types.Receipt, error) { var logs []*types.ReceiptLog var kv []*types.KeyValue @@ -742,7 +742,7 @@ func (action *Action) GameAbort(pbend *gty.GuessGameAbort) (*types.Receipt, erro return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//getOptions 获得竞猜选项,并判断是否符合约定格式,类似"A:xxxx;B:xxxx;C:xxx",“:”前为选项名称,不能重复,":"后为选项说明。 +// getOptions 获得竞猜选项,并判断是否符合约定格式,类似"A:xxxx;B:xxxx;C:xxx",“:”前为选项名称,不能重复,":"后为选项说明。 func getOptions(strOptions string) (options []string, legal bool) { if len(strOptions) == 0 { return nil, false @@ -765,7 +765,7 @@ func getOptions(strOptions string) (options []string, legal bool) { return options, legal } -//trimStr 去除字符串中的空格、制表符、换行符 +// trimStr 去除字符串中的空格、制表符、换行符 func trimStr(str string) string { str = strings.Replace(str, " ", "", -1) str = strings.Replace(str, "\t", "", -1) @@ -774,7 +774,7 @@ func trimStr(str string) string { return str } -//isLegalOption 判断选项是否为合法选项 +// isLegalOption 判断选项是否为合法选项 func isLegalOption(options []string, option string) bool { option = trimStr(option) for i := 0; i < len(options); i++ { @@ -786,7 +786,7 @@ func isLegalOption(options []string, option string) bool { return false } -//changeStatus 修改游戏状态,同步更新历史记录 +// changeStatus 修改游戏状态,同步更新历史记录 func (action *Action) changeStatus(game *gty.GuessGame, destStatus int32) { if game.Status != destStatus { game.PreStatus = game.Status @@ -796,7 +796,7 @@ func (action *Action) changeStatus(game *gty.GuessGame, destStatus int32) { } } -//changeAllAddrIndex 状态更新时,更新下注记录的历史信息 +// changeAllAddrIndex 状态更新时,更新下注记录的历史信息 func (action *Action) changeAllAddrIndex(game *gty.GuessGame) { for i := 0; i < len(game.Plays); i++ { player := game.Plays[i] @@ -805,7 +805,7 @@ func (action *Action) changeAllAddrIndex(game *gty.GuessGame) { } } -//refreshStatusByTime 检测游戏是否过期,是否可以下注 +// refreshStatusByTime 检测游戏是否过期,是否可以下注 func (action *Action) refreshStatusByTime(game *gty.GuessGame) (canBet bool) { mainHeight := action.mainHeight //如果完全由管理员驱动状态变化,则除了保护性过期判断外,不需要做其他判断。 @@ -839,7 +839,7 @@ func (action *Action) refreshStatusByTime(game *gty.GuessGame) (canBet bool) { return canBet } -//checkTime 检测游戏的过期设置。 +// checkTime 检测游戏的过期设置。 func (action *Action) checkTime(start *gty.GuessGameStart) bool { if start.MaxBetHeight == 0 && start.ExpireHeight == 0 { //如果上述字段都不携带,则认为完全由admin的指令驱动。 diff --git a/plugin/dapp/guess/executor/query.go b/plugin/dapp/guess/executor/query.go index d5ef8c87f6..3a30d0d4b8 100644 --- a/plugin/dapp/guess/executor/query.go +++ b/plugin/dapp/guess/executor/query.go @@ -12,12 +12,12 @@ import ( gty "github.com/33cn/plugin/plugin/dapp/guess/types" ) -//Query_QueryGamesByIDs method +// Query_QueryGamesByIDs method func (g *Guess) Query_QueryGamesByIDs(in *gty.QueryGuessGameInfos) (types.Message, error) { return queryGameInfos(g.GetLocalDB(), in) } -//Query_QueryGameByID method +// Query_QueryGameByID method func (g *Guess) Query_QueryGameByID(in *gty.QueryGuessGameInfo) (types.Message, error) { game, err := queryGameInfo(g.GetLocalDB(), []byte(in.GetGameID())) if err != nil { @@ -27,7 +27,7 @@ func (g *Guess) Query_QueryGameByID(in *gty.QueryGuessGameInfo) (types.Message, return >y.ReplyGuessGameInfo{Game: game}, nil } -//Query_QueryGamesByAddr method +// Query_QueryGamesByAddr method func (g *Guess) Query_QueryGamesByAddr(in *gty.QueryGuessGameInfo) (types.Message, error) { gameTable := gty.NewGuessUserTable(g.GetLocalDB()) query := gameTable.GetQuery(g.GetLocalDB()) @@ -35,7 +35,7 @@ func (g *Guess) Query_QueryGamesByAddr(in *gty.QueryGuessGameInfo) (types.Messag return queryUserTableData(query, "addr", []byte(in.Addr), []byte(in.PrimaryKey)) } -//Query_QueryGamesByStatus method +// Query_QueryGamesByStatus method func (g *Guess) Query_QueryGamesByStatus(in *gty.QueryGuessGameInfo) (types.Message, error) { gameTable := gty.NewGuessGameTable(g.GetLocalDB()) query := gameTable.GetQuery(g.GetLocalDB()) @@ -43,7 +43,7 @@ func (g *Guess) Query_QueryGamesByStatus(in *gty.QueryGuessGameInfo) (types.Mess return queryGameTableData(query, "status", []byte(fmt.Sprintf("%2d", in.Status)), []byte(in.PrimaryKey)) } -//Query_QueryGamesByAdminAddr method +// Query_QueryGamesByAdminAddr method func (g *Guess) Query_QueryGamesByAdminAddr(in *gty.QueryGuessGameInfo) (types.Message, error) { gameTable := gty.NewGuessGameTable(g.GetLocalDB()) query := gameTable.GetQuery(g.GetLocalDB()) @@ -51,7 +51,7 @@ func (g *Guess) Query_QueryGamesByAdminAddr(in *gty.QueryGuessGameInfo) (types.M return queryGameTableData(query, "admin", prefix, []byte(in.PrimaryKey)) } -//Query_QueryGamesByAddrStatus method +// Query_QueryGamesByAddrStatus method func (g *Guess) Query_QueryGamesByAddrStatus(in *gty.QueryGuessGameInfo) (types.Message, error) { userTable := gty.NewGuessUserTable(g.GetLocalDB()) gameTable := gty.NewGuessGameTable(g.GetLocalDB()) @@ -65,7 +65,7 @@ func (g *Guess) Query_QueryGamesByAddrStatus(in *gty.QueryGuessGameInfo) (types. return queryJoinTableData(tableJoin, "addr#status", prefix, []byte(in.PrimaryKey)) } -//Query_QueryGamesByAdminStatus method +// Query_QueryGamesByAdminStatus method func (g *Guess) Query_QueryGamesByAdminStatus(in *gty.QueryGuessGameInfo) (types.Message, error) { gameTable := gty.NewGuessGameTable(g.GetLocalDB()) query := gameTable.GetQuery(g.GetLocalDB()) @@ -74,7 +74,7 @@ func (g *Guess) Query_QueryGamesByAdminStatus(in *gty.QueryGuessGameInfo) (types return queryGameTableData(query, "admin_status", prefix, []byte(in.PrimaryKey)) } -//Query_QueryGamesByCategoryStatus method +// Query_QueryGamesByCategoryStatus method func (g *Guess) Query_QueryGamesByCategoryStatus(in *gty.QueryGuessGameInfo) (types.Message, error) { gameTable := gty.NewGuessGameTable(g.GetLocalDB()) query := gameTable.GetQuery(g.GetLocalDB()) diff --git a/plugin/dapp/guess/rpc/guess_test.go b/plugin/dapp/guess/rpc/guess_test.go index e7a28e20f9..0effd2db06 100644 --- a/plugin/dapp/guess/rpc/guess_test.go +++ b/plugin/dapp/guess/rpc/guess_test.go @@ -484,7 +484,7 @@ func testGuessImp(t *testing.T) { if !ok { fmt.Println("Guess stopped, bet failed.") } else { - fmt.Println(fmt.Sprintf("Guess A bet txid: %s", hex.EncodeToString(txid))) + fmt.Printf("Guess A bet txid: %s\n", hex.EncodeToString(txid)) } time.Sleep(2 * time.Second) reply = queryGuessByIds(strGameID1) @@ -495,7 +495,7 @@ func testGuessImp(t *testing.T) { if !ok { fmt.Println("sendGuessPublishTx failed,only admin can publish.") } else { - fmt.Println(fmt.Sprintf("publish ok, but it's not correct, txid: %s", hex.EncodeToString(txid))) + fmt.Printf("publish ok, but it's not correct, txid: %s\n", hex.EncodeToString(txid)) } time.Sleep(2 * time.Second) reply = queryGuessByIds(strGameID1) @@ -506,7 +506,7 @@ func testGuessImp(t *testing.T) { if !ok { fmt.Println("sendGuessPublishTx failed.") } else { - fmt.Println(fmt.Sprintf("publish ok, txid: %s", hex.EncodeToString(txid))) + fmt.Printf("publish ok, txid: %s\n", hex.EncodeToString(txid)) } time.Sleep(2 * time.Second) reply = queryGuessByIds(strGameID1) @@ -517,7 +517,7 @@ func testGuessImp(t *testing.T) { if !ok { fmt.Println("Guess abort failed, already published.") } else { - fmt.Println(fmt.Sprintf("Guess abort txid: %s", hex.EncodeToString(txid))) + fmt.Printf("Guess abort txid: %s\n", hex.EncodeToString(txid)) } time.Sleep(2 * time.Second) reply = queryGuessByIds(strGameID1) @@ -543,7 +543,7 @@ func testGuessImp(t *testing.T) { if !ok { fmt.Println("Guess abort failed.") } else { - fmt.Println(fmt.Sprintf("Guess abort txid: %s", hex.EncodeToString(txid))) + fmt.Printf("Guess abort txid: %s\n", hex.EncodeToString(txid)) } time.Sleep(2 * time.Second) reply = queryGuessByIds(strGameID2) @@ -554,7 +554,7 @@ func testGuessImp(t *testing.T) { if !ok { fmt.Println("Guess stop failed,it's already aborted.") } else { - fmt.Println(fmt.Sprintf("Guess stop txid: %s", hex.EncodeToString(txid))) + fmt.Printf("Guess stop txid: %s\n", hex.EncodeToString(txid)) } time.Sleep(2 * time.Second) reply = queryGuessByIds(strGameID2) @@ -590,7 +590,7 @@ func testGuessImp(t *testing.T) { if !ok { fmt.Println("Guess abort failed.") } else { - fmt.Println(fmt.Sprintf("Guess abort txid: %s", hex.EncodeToString(txid))) + fmt.Printf("Guess abort txid: %s\n", hex.EncodeToString(txid)) } time.Sleep(2 * time.Second) diff --git a/plugin/dapp/guess/types/const.go b/plugin/dapp/guess/types/const.go index 0d538f8a72..1b9326ced9 100644 --- a/plugin/dapp/guess/types/const.go +++ b/plugin/dapp/guess/types/const.go @@ -4,7 +4,7 @@ package types -//game action ty +// game action ty const ( GuessGameActionStart = 5 GuessGameActionBet = 6 @@ -21,7 +21,7 @@ const ( GuessGameStatusTimeOut = 16 ) -//game log ty +// game log ty const ( TyLogGuessGameStart = 901 TyLogGuessGameBet = 902 @@ -31,9 +31,9 @@ const ( TyLogGuessGameTimeout = 906 ) -//包的名字可以通过配置文件来配置 -//建议用github的组织名称,或者用户名字开头, 再加上自己的插件的名字 -//如果发生重名,可以通过配置文件修改这些名字 +// 包的名字可以通过配置文件来配置 +// 建议用github的组织名称,或者用户名字开头, 再加上自己的插件的名字 +// 如果发生重名,可以通过配置文件修改这些名字 var ( GuessX = "guess" ExecerGuess = []byte(GuessX) diff --git a/plugin/dapp/guess/types/table.go b/plugin/dapp/guess/types/table.go index 04dd292efd..9417167889 100644 --- a/plugin/dapp/guess/types/table.go +++ b/plugin/dapp/guess/types/table.go @@ -22,7 +22,7 @@ var opt_guess_user = &table.Option{ Index: []string{"addr", "startindex"}, } -//NewGuessUserTable 新建表 +// NewGuessUserTable 新建表 func NewGuessUserTable(kvdb db.KV) *table.Table { rowmeta := NewGuessUserRow() table, err := table.NewTable(rowmeta, kvdb, opt_guess_user) @@ -32,22 +32,22 @@ func NewGuessUserTable(kvdb db.KV) *table.Table { return table } -//GuessUserRow table meta 结构 +// GuessUserRow table meta 结构 type GuessUserRow struct { *UserBet } -//NewGuessUserRow 新建一个meta 结构 +// NewGuessUserRow 新建一个meta 结构 func NewGuessUserRow() *GuessUserRow { return &GuessUserRow{UserBet: &UserBet{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存eventid) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存eventid) func (tx *GuessUserRow) CreateRow() *table.Row { return &table.Row{Data: &UserBet{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (tx *GuessUserRow) SetPayload(data types.Message) error { if txdata, ok := data.(*UserBet); ok { tx.UserBet = txdata @@ -56,7 +56,7 @@ func (tx *GuessUserRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (tx *GuessUserRow) Get(key string) ([]byte, error) { if key == "index" { return []byte(fmt.Sprintf("%018d", tx.Index)), nil @@ -76,7 +76,7 @@ var opt_guess_game = &table.Option{ Index: []string{"gameid", "status", "admin", "admin_status", "category_status"}, } -//NewGuessGameTable 新建表 +// NewGuessGameTable 新建表 func NewGuessGameTable(kvdb db.KV) *table.Table { rowmeta := NewGuessGameRow() table, err := table.NewTable(rowmeta, kvdb, opt_guess_game) @@ -86,22 +86,22 @@ func NewGuessGameTable(kvdb db.KV) *table.Table { return table } -//GuessGameRow table meta 结构 +// GuessGameRow table meta 结构 type GuessGameRow struct { *GuessGame } -//NewGuessGameRow 新建一个meta 结构 +// NewGuessGameRow 新建一个meta 结构 func NewGuessGameRow() *GuessGameRow { return &GuessGameRow{GuessGame: &GuessGame{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存eventid) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存eventid) func (tx *GuessGameRow) CreateRow() *table.Row { return &table.Row{Data: &GuessGame{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (tx *GuessGameRow) SetPayload(data types.Message) error { if txdata, ok := data.(*GuessGame); ok { tx.GuessGame = txdata @@ -110,7 +110,7 @@ func (tx *GuessGameRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (tx *GuessGameRow) Get(key string) ([]byte, error) { if key == "startindex" { return []byte(fmt.Sprintf("%018d", tx.StartIndex)), nil diff --git a/plugin/dapp/guess/types/types.go b/plugin/dapp/guess/types/types.go index cd264fcb8a..f728e88e5b 100644 --- a/plugin/dapp/guess/types/types.go +++ b/plugin/dapp/guess/types/types.go @@ -17,12 +17,12 @@ func init() { types.RegExec(GuessX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(GuessX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(GuessX, NewType(cfg)) } diff --git a/plugin/dapp/hashlock/executor/hashlock.go b/plugin/dapp/hashlock/executor/hashlock.go index 253e6dc5b7..7145184303 100755 --- a/plugin/dapp/hashlock/executor/hashlock.go +++ b/plugin/dapp/hashlock/executor/hashlock.go @@ -22,7 +22,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Hashlock{})) diff --git a/plugin/dapp/hashlock/executor/hashlock_unit_test.go b/plugin/dapp/hashlock/executor/hashlock_unit_test.go index e019effe70..e27d45dab6 100755 --- a/plugin/dapp/hashlock/executor/hashlock_unit_test.go +++ b/plugin/dapp/hashlock/executor/hashlock_unit_test.go @@ -79,7 +79,7 @@ func TestExecHashlock(t *testing.T) { } } -//timelimit +// timelimit func TestExecHashunlock(t *testing.T) { var targetReceipt types.Receipt diff --git a/plugin/dapp/hashlock/types/hashlock.go b/plugin/dapp/hashlock/types/hashlock.go index a0c00b626a..487addcedb 100755 --- a/plugin/dapp/hashlock/types/hashlock.go +++ b/plugin/dapp/hashlock/types/hashlock.go @@ -23,13 +23,13 @@ func init() { types.RegExec(HashlockX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(HashlockX, "Enable", 0) cfg.RegisterDappFork(HashlockX, ForkBadRepeatSecretX, 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(HashlockX, NewType(cfg)) } diff --git a/plugin/dapp/issuance/commands/cmd.go b/plugin/dapp/issuance/commands/cmd.go index d9ad3ae46f..b3b5c98492 100644 --- a/plugin/dapp/issuance/commands/cmd.go +++ b/plugin/dapp/issuance/commands/cmd.go @@ -51,7 +51,7 @@ func addIssuanceCreateFlags(cmd *cobra.Command) { cmd.Flags().Uint64P("period", "p", 0, "period") } -//IssuanceCreate .... +// IssuanceCreate .... func IssuanceCreate(cmd *cobra.Command, args []string) { paraName, _ := cmd.Flags().GetString("paraName") @@ -91,7 +91,7 @@ func addIssuanceDebtFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("value") } -//IssuanceDebt ... +// IssuanceDebt ... func IssuanceDebt(cmd *cobra.Command, args []string) { paraName, _ := cmd.Flags().GetString("paraName") @@ -128,7 +128,7 @@ func addIssuanceRepayFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("debtID") } -//IssuanceRepay ... +// IssuanceRepay ... func IssuanceRepay(cmd *cobra.Command, args []string) { paraName, _ := cmd.Flags().GetString("paraName") @@ -165,7 +165,7 @@ func addIssuancePriceFeedFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("volume") } -//IssuancePriceFeed ... +// IssuancePriceFeed ... func IssuancePriceFeed(cmd *cobra.Command, args []string) { paraName, _ := cmd.Flags().GetString("paraName") @@ -200,7 +200,7 @@ func addIssuanceCloseFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("issuanceID") } -//IssuanceClose ... +// IssuanceClose ... func IssuanceClose(cmd *cobra.Command, args []string) { paraName, _ := cmd.Flags().GetString("paraName") @@ -234,7 +234,7 @@ func addIssuanceManageFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("addr") } -//IssuanceManage ... +// IssuanceManage ... func IssuanceManage(cmd *cobra.Command, args []string) { paraName, _ := cmd.Flags().GetString("paraName") @@ -252,7 +252,7 @@ func IssuanceManage(cmd *cobra.Command, args []string) { ctx.RunWithoutMarshal() } -//IssuacneQueryPriceCmd ... +// IssuacneQueryPriceCmd ... func IssuacneQueryPriceCmd() *cobra.Command { cmd := &cobra.Command{ Use: "price", @@ -262,7 +262,7 @@ func IssuacneQueryPriceCmd() *cobra.Command { return cmd } -//IssuanceQueryPrice ... +// IssuanceQueryPrice ... func IssuanceQueryPrice(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") @@ -275,7 +275,7 @@ func IssuanceQueryPrice(cmd *cobra.Command, args []string) { ctx.Run() } -//IssuanceQueryUserBalanceCmd ... +// IssuanceQueryUserBalanceCmd ... func IssuanceQueryUserBalanceCmd() *cobra.Command { cmd := &cobra.Command{ Use: "balance", @@ -291,7 +291,7 @@ func addIssuanceQueryBalanceFlags(cmd *cobra.Command) { cmd.MarkFlagRequired("address") } -//IssuanceQueryUserBalance ... +// IssuanceQueryUserBalance ... func IssuanceQueryUserBalance(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") addr, _ := cmd.Flags().GetString("address") @@ -333,7 +333,7 @@ func addIssuanceQueryFlags(cmd *cobra.Command) { cmd.Flags().StringP("debtID", "d", "", "debt ID") } -//IssuanceQuery ... +// IssuanceQuery ... func IssuanceQuery(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") issuanceID, _ := cmd.Flags().GetString("issuanceID") diff --git a/plugin/dapp/issuance/executor/issuance.go b/plugin/dapp/issuance/executor/issuance.go index 000d4665af..6ba91a48d9 100644 --- a/plugin/dapp/issuance/executor/issuance.go +++ b/plugin/dapp/issuance/executor/issuance.go @@ -14,7 +14,7 @@ import ( var clog = log.New("module", "execs.issuance") var driverName = pty.IssuanceX -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Issuance{})) diff --git a/plugin/dapp/issuance/executor/issuancedb.go b/plugin/dapp/issuance/executor/issuancedb.go index 22432f00ba..6515268324 100644 --- a/plugin/dapp/issuance/executor/issuancedb.go +++ b/plugin/dapp/issuance/executor/issuancedb.go @@ -26,7 +26,7 @@ const ( MaxCount = int32(100) // 最多取100条 ) -//setting +// setting const ( DefaultDebtCeiling = 100000 // 默认借贷限额 DefaultLiquidationRatio = 0.25 * 1e4 // 默认质押比 diff --git a/plugin/dapp/issuance/executor/query.go b/plugin/dapp/issuance/executor/query.go index 69a3841deb..71313bce61 100644 --- a/plugin/dapp/issuance/executor/query.go +++ b/plugin/dapp/issuance/executor/query.go @@ -9,7 +9,7 @@ import ( pty "github.com/33cn/plugin/plugin/dapp/issuance/types" ) -//Query_IssuanceInfoByID ... +// Query_IssuanceInfoByID ... func (c *Issuance) Query_IssuanceInfoByID(req *pty.ReqIssuanceInfo) (types.Message, error) { issu, err := queryIssuanceByID(c.GetStateDB(), req.IssuanceId) if err != nil { @@ -31,7 +31,7 @@ func (c *Issuance) Query_IssuanceInfoByID(req *pty.ReqIssuanceInfo) (types.Messa }, nil } -//Query_IssuanceInfoByIDs ... +// Query_IssuanceInfoByIDs ... func (c *Issuance) Query_IssuanceInfoByIDs(req *pty.ReqIssuanceInfos) (types.Message, error) { infos := &pty.RepIssuanceCurrentInfos{} for _, id := range req.IssuanceIds { @@ -58,7 +58,7 @@ func (c *Issuance) Query_IssuanceInfoByIDs(req *pty.ReqIssuanceInfos) (types.Mes return infos, nil } -//Query_IssuanceByStatus ... +// Query_IssuanceByStatus ... func (c *Issuance) Query_IssuanceByStatus(req *pty.ReqIssuanceByStatus) (types.Message, error) { ids := &pty.RepIssuanceIDs{} issuIDs, err := queryIssuanceByStatus(c.GetLocalDB(), req.Status, req.IssuanceId) @@ -71,7 +71,7 @@ func (c *Issuance) Query_IssuanceByStatus(req *pty.ReqIssuanceByStatus) (types.M return ids, nil } -//Query_IssuanceRecordByID ... +// Query_IssuanceRecordByID ... func (c *Issuance) Query_IssuanceRecordByID(req *pty.ReqIssuanceRecords) (types.Message, error) { ret := &pty.RepIssuanceDebtInfo{} issuRecord, err := queryIssuanceRecordByID(c.GetStateDB(), req.IssuanceId, req.DebtId) @@ -84,7 +84,7 @@ func (c *Issuance) Query_IssuanceRecordByID(req *pty.ReqIssuanceRecords) (types. return ret, nil } -//Query_IssuanceRecordsByAddr ... +// Query_IssuanceRecordsByAddr ... func (c *Issuance) Query_IssuanceRecordsByAddr(req *pty.ReqIssuanceRecords) (types.Message, error) { ret := &pty.RepIssuanceRecords{} records, err := queryIssuanceRecordByAddr(c.GetStateDB(), c.GetLocalDB(), req.Addr, req.Status, req.DebtId) @@ -106,7 +106,7 @@ func (c *Issuance) Query_IssuanceRecordsByAddr(req *pty.ReqIssuanceRecords) (typ return ret, nil } -//Query_IssuanceRecordsByStatus ... +// Query_IssuanceRecordsByStatus ... func (c *Issuance) Query_IssuanceRecordsByStatus(req *pty.ReqIssuanceRecords) (types.Message, error) { ret := &pty.RepIssuanceRecords{} records, err := queryIssuanceRecordsByStatus(c.GetStateDB(), c.GetLocalDB(), req.Status, req.DebtId) @@ -119,7 +119,7 @@ func (c *Issuance) Query_IssuanceRecordsByStatus(req *pty.ReqIssuanceRecords) (t return ret, nil } -//Query_IssuancePrice ... +// Query_IssuancePrice ... func (c *Issuance) Query_IssuancePrice(req *pty.ReqIssuanceRecords) (types.Message, error) { price, err := getLatestPrice(c.GetStateDB()) if err != nil { @@ -130,7 +130,7 @@ func (c *Issuance) Query_IssuancePrice(req *pty.ReqIssuanceRecords) (types.Messa return &pty.RepIssuancePrice{Price: price}, nil } -//Query_IssuanceUserBalance ... +// Query_IssuanceUserBalance ... func (c *Issuance) Query_IssuanceUserBalance(req *pty.ReqIssuanceRecords) (types.Message, error) { balance, err := queryIssuanceUserBalance(c.GetStateDB(), c.GetLocalDB(), req.Addr) if err != nil { diff --git a/plugin/dapp/issuance/types/issuance.go b/plugin/dapp/issuance/types/issuance.go index 213f95b1da..1425dfdd9d 100644 --- a/plugin/dapp/issuance/types/issuance.go +++ b/plugin/dapp/issuance/types/issuance.go @@ -26,14 +26,14 @@ func init() { types.RegExec(IssuanceX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(IssuanceX, "Enable", 0) cfg.RegisterDappFork(IssuanceX, ForkIssuanceTableUpdate, 0) cfg.RegisterDappFork(IssuanceX, ForkIssuancePrecision, 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(IssuanceX, NewType(cfg)) } diff --git a/plugin/dapp/issuance/types/table.go b/plugin/dapp/issuance/types/table.go index 271d9ea8f4..cefcf1af5d 100644 --- a/plugin/dapp/issuance/types/table.go +++ b/plugin/dapp/issuance/types/table.go @@ -16,7 +16,7 @@ var opt = &table.Option{ Index: []string{"status"}, } -//NewIssuanceTable 新建表 +// NewIssuanceTable 新建表 func NewIssuanceTable(kvdb db.KV) *table.Table { rowmeta := NewIssuanceRow() table, err := table.NewTable(rowmeta, kvdb, opt) @@ -26,22 +26,22 @@ func NewIssuanceTable(kvdb db.KV) *table.Table { return table } -//IssuanceRow table meta 结构 +// IssuanceRow table meta 结构 type IssuanceRow struct { *ReceiptIssuanceID } -//NewIssuanceRow 新建一个meta 结构 +// NewIssuanceRow 新建一个meta 结构 func NewIssuanceRow() *IssuanceRow { return &IssuanceRow{ReceiptIssuanceID: &ReceiptIssuanceID{}} } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (tx *IssuanceRow) CreateRow() *table.Row { return &table.Row{Data: &ReceiptIssuanceID{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (tx *IssuanceRow) SetPayload(data types.Message) error { if txdata, ok := data.(*ReceiptIssuanceID); ok { tx.ReceiptIssuanceID = txdata @@ -50,7 +50,7 @@ func (tx *IssuanceRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (tx *IssuanceRow) Get(key string) ([]byte, error) { if key == "issuanceid" { return []byte(tx.IssuanceId), nil @@ -77,22 +77,22 @@ func NewRecordTable(kvdb db.KV) *table.Table { return table } -//IssuanceRecordRow table meta 结构 +// IssuanceRecordRow table meta 结构 type IssuanceRecordRow struct { *ReceiptIssuance } -//NewRecordRow 新建一个meta 结构 +// NewRecordRow 新建一个meta 结构 func NewRecordRow() *IssuanceRecordRow { return &IssuanceRecordRow{ReceiptIssuance: &ReceiptIssuance{}} } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (tx *IssuanceRecordRow) CreateRow() *table.Row { return &table.Row{Data: &ReceiptIssuance{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (tx *IssuanceRecordRow) SetPayload(data types.Message) error { if txdata, ok := data.(*ReceiptIssuance); ok { tx.ReceiptIssuance = txdata @@ -101,7 +101,7 @@ func (tx *IssuanceRecordRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (tx *IssuanceRecordRow) Get(key string) ([]byte, error) { if key == "debtid" { return []byte(tx.DebtId), nil diff --git a/plugin/dapp/issuance/types/types.go b/plugin/dapp/issuance/types/types.go index 553473fc2a..ce004e6f09 100644 --- a/plugin/dapp/issuance/types/types.go +++ b/plugin/dapp/issuance/types/types.go @@ -4,7 +4,7 @@ package types -//Issuance op +// Issuance op const ( IssuanceActionCreate = 1 + iota // 创建借贷 IssuanceActionDebt // 大户抵押 @@ -28,13 +28,13 @@ const ( IssuancePreLiquidationRatio = 11000 //TODO 预清算比例,抵押物价值跌到借出ccny价值110%的时候开始清算 ) -//Issuance status +// Issuance status const ( IssuanceStatusCreated = 1 + iota IssuanceStatusClose ) -//status ... +// status ... const ( IssuanceUserStatusCreate = 1 + iota IssuanceUserStatusWarning @@ -44,7 +44,7 @@ const ( IssuanceUserStatusClose ) -//type ... +// type ... const ( PriceFeedKey = "issuance-price-feed" GuarantorKey = "issuance-guarantor" @@ -52,7 +52,7 @@ const ( FundKey = "issuance-fund" ) -//fork ... +// fork ... var ( ForkIssuanceTableUpdate = "ForkIssuanceTableUpdate" ForkIssuancePrecision = "ForkIssuancePrecision" diff --git a/plugin/dapp/js/command/js.go b/plugin/dapp/js/command/js.go index eadd36f092..d4319e07cc 100644 --- a/plugin/dapp/js/command/js.go +++ b/plugin/dapp/js/command/js.go @@ -19,7 +19,7 @@ import ( "github.com/spf13/cobra" ) -//JavaScriptCmd : +// JavaScriptCmd : func JavaScriptCmd() *cobra.Command { cmd := &cobra.Command{ Use: "jsvm", @@ -120,7 +120,7 @@ func callJavaScript(cmd *cobra.Command, args []string) { ctx.RunWithoutMarshal() } -//JavaScriptQueryCmd : +// JavaScriptQueryCmd : func JavaScriptQueryCmd() *cobra.Command { cmd := &cobra.Command{ Use: "query", diff --git a/plugin/dapp/js/executor/account.go b/plugin/dapp/js/executor/account.go index 85586a2dd2..f49b6ea0c5 100644 --- a/plugin/dapp/js/executor/account.go +++ b/plugin/dapp/js/executor/account.go @@ -9,15 +9,16 @@ import ( /* //chain33 相关的账户操作函数 (操作某个execer 下面的 symbol) -function Account(execer, symbol) { - this.execer = execer - this.symbol = symbol -} -func Receipt(kvs, logs) { - this.kvs = kvs - this.logs = logs -} + function Account(execer, symbol) { + this.execer = execer + this.symbol = symbol + } + + func Receipt(kvs, logs) { + this.kvs = kvs + this.logs = logs + } var obj = new Account(execer, symbol) //init 函数才能使用的两个函数(或者增发) diff --git a/plugin/dapp/js/executor/js.go b/plugin/dapp/js/executor/js.go index caeecc80d0..f7fd85b04e 100644 --- a/plugin/dapp/js/executor/js.go +++ b/plugin/dapp/js/executor/js.go @@ -23,7 +23,7 @@ var codecache *lru.Cache var isinit int64 -//Init 插件初始化 +// Init 插件初始化 func Init(name string, cfg *types.Chain33Config, sub []byte) { if atomic.CompareAndSwapInt64(&isinit, 0, 1) { //最新的64个code做cache @@ -37,7 +37,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&js{})) @@ -64,12 +64,12 @@ func newjs() drivers.Driver { return t } -//GetName 获取名字 +// GetName 获取名字 func GetName() string { return newjs().GetName() } -//GetDriverName 获取插件的名字 +// GetDriverName 获取插件的名字 func (u *js) GetDriverName() string { return driverName } diff --git a/plugin/dapp/js/executor/jsvm_test.go b/plugin/dapp/js/executor/jsvm_test.go index 539f730f3f..67b36f9a1d 100644 --- a/plugin/dapp/js/executor/jsvm_test.go +++ b/plugin/dapp/js/executor/jsvm_test.go @@ -148,7 +148,7 @@ func TestCallError(t *testing.T) { assert.Equal(t, true, strings.Contains(err.Error(), ptypes.ErrFuncNotFound.Error())) } -//数字非常大的数字的处理 +// 数字非常大的数字的处理 func TestBigInt(t *testing.T) { dir, ldb, kvdb := util.CreateTestDB() defer util.CloseTestDB(dir, ldb) diff --git a/plugin/dapp/js/executor/runtime.go b/plugin/dapp/js/executor/runtime.go index 3cd56b77ae..f4660fdd44 100644 --- a/plugin/dapp/js/executor/runtime.go +++ b/plugin/dapp/js/executor/runtime.go @@ -6,7 +6,7 @@ import ( "github.com/robertkrimen/otto" ) -//让 js 具有访问 区块链 的一些能力 +// 让 js 具有访问 区块链 的一些能力 func execaddressFunc(vm *otto.Otto) { vm.Set("execaddress", func(call otto.FunctionCall) otto.Value { key, err := call.Argument(0).ToString() diff --git a/plugin/dapp/js/executor/table.go b/plugin/dapp/js/executor/table.go index ddeab7362b..ea15e3e68c 100644 --- a/plugin/dapp/js/executor/table.go +++ b/plugin/dapp/js/executor/table.go @@ -37,7 +37,7 @@ import ( } */ -//NewTable 创建一个新的表格, 返回handle +// NewTable 创建一个新的表格, 返回handle func (u *js) newTable(name, config, defaultvalue string) (id int64, err error) { u.globalHanldeID++ id = u.globalHanldeID @@ -96,7 +96,7 @@ func (u *js) newTableFunc(vm *otto.Otto, name string) { }) } -//CloseTable 关闭表格释放内存 +// CloseTable 关闭表格释放内存 func (u *js) closeTable(id int64) error { _, ok := u.globalTableHandle.Load(id) if !ok { @@ -410,7 +410,7 @@ handle := new_join_table(left, right, listofjoinindex) //join table 的操作(接口完全相同) //handle3 := new_table(newcofifg{config1, config2}) -//JSONRow meta +// JSONRow meta type JSONRow struct { *jsproto.JsLog config map[string]string @@ -421,7 +421,7 @@ type JSONRow struct { defaultvalue string } -//NewJSONRow 创建一个row +// NewJSONRow 创建一个row func NewJSONRow(config string, defaultvalue string) (*JSONRow, error) { row := &JSONRow{} row.isint = regexp.MustCompile(`%\d*d`) @@ -440,7 +440,7 @@ func NewJSONRow(config string, defaultvalue string) (*JSONRow, error) { return row, nil } -//CreateRow 创建一行 +// CreateRow 创建一行 func (row *JSONRow) CreateRow() *table.Row { return &table.Row{Data: &jsproto.JsLog{Data: row.defaultvalue}} } @@ -452,7 +452,7 @@ func (row *JSONRow) parse() error { return d.Decode(&row.data) } -//SetPayload 设置行的内容 +// SetPayload 设置行的内容 func (row *JSONRow) SetPayload(data types.Message) error { if row.lastdata == data { return nil @@ -465,7 +465,7 @@ func (row *JSONRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get value of row +// Get value of row func (row *JSONRow) Get(key string) ([]byte, error) { v, err := row.get(key) return v, err diff --git a/plugin/dapp/js/types/js.go b/plugin/dapp/js/types/js.go index 2b5a4e2275..db51e46c4e 100644 --- a/plugin/dapp/js/types/js.go +++ b/plugin/dapp/js/types/js.go @@ -14,7 +14,7 @@ const ( jsActionCall = 1 ) -//日志类型 +// 日志类型 const ( TyLogJs = 10000 ) @@ -32,10 +32,10 @@ var ( } ) -//JsX 插件名字 +// JsX 插件名字 var JsX = "jsvm" -//错误常量 +// 错误常量 var ( ErrDupName = errors.New("ErrDupName") ErrJsReturnNotObject = errors.New("ErrJsReturnNotObject") @@ -60,22 +60,22 @@ func init() { types.RegExec(JsX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(JsX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(JsX, NewType(cfg)) } -//JsType 类型 +// JsType 类型 type JsType struct { types.ExecTypeBase } -//NewType 新建一个plugin 类型 +// NewType 新建一个plugin 类型 func NewType(cfg *types.Chain33Config) *JsType { c := &JsType{} c.SetChild(c) @@ -83,17 +83,17 @@ func NewType(cfg *types.Chain33Config) *JsType { return c } -//GetPayload 获取 交易构造 +// GetPayload 获取 交易构造 func (t *JsType) GetPayload() types.Message { return &jsproto.JsAction{} } -//GetTypeMap 获取类型映射 +// GetTypeMap 获取类型映射 func (t *JsType) GetTypeMap() map[string]int32 { return typeMap } -//GetLogMap 获取日志映射 +// GetLogMap 获取日志映射 func (t *JsType) GetLogMap() map[int64]*types.LogInfo { return logMap } diff --git a/plugin/dapp/lightclient/lighttypes/lightclient.pb.go b/plugin/dapp/lightclient/lighttypes/lightclient.pb.go index b781ec0e98..9c1b6df1ec 100644 --- a/plugin/dapp/lightclient/lighttypes/lightclient.pb.go +++ b/plugin/dapp/lightclient/lighttypes/lightclient.pb.go @@ -8,11 +8,12 @@ package lighttypes import ( context "context" + reflect "reflect" + sync "sync" + grpc "google.golang.org/grpc" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" ) const ( diff --git a/plugin/dapp/lightclient/rpc/lightclient/neutrino/tss.go b/plugin/dapp/lightclient/rpc/lightclient/neutrino/tss.go index 0b6ab73197..47454cb6a2 100644 --- a/plugin/dapp/lightclient/rpc/lightclient/neutrino/tss.go +++ b/plugin/dapp/lightclient/rpc/lightclient/neutrino/tss.go @@ -426,7 +426,7 @@ func (t *tssService) validateWithdrawTx(tx *wire.MsgTx, inputAmounts []int64, re totalOutput += out.Value } fee := totalInput - totalOutput - expectedFee := int64(estimateBtcFee(tx, btcutil.Amount(req.feeRate))) + expectedFee := int64(estimateBtcFee(tx, req.feeRate)) // 控制手续费在合理范围内 if fee > 2*expectedFee || fee < 0 { log.Error("validateWithdrawSignNotify invalid fee", "fee", fee, "expected", expectedFee, diff --git a/plugin/dapp/lottery/executor/lottery.go b/plugin/dapp/lottery/executor/lottery.go index abb2ce9c9b..cd3880d034 100755 --- a/plugin/dapp/lottery/executor/lottery.go +++ b/plugin/dapp/lottery/executor/lottery.go @@ -36,7 +36,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Lottery{})) diff --git a/plugin/dapp/lottery/executor/lotterydb.go b/plugin/dapp/lottery/executor/lotterydb.go index d0afe27785..6ba4274ee4 100755 --- a/plugin/dapp/lottery/executor/lotterydb.go +++ b/plugin/dapp/lottery/executor/lotterydb.go @@ -540,7 +540,7 @@ func (action *Action) LotteryClose(draw *pty.LotteryClose) (*types.Receipt, erro return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//random used for verification in solo +// random used for verification in solo func (action *Action) findLuckyNum(isSolo bool, lott *LotteryDB) (int64, error) { var num int64 if isSolo { diff --git a/plugin/dapp/lottery/types/lottery.go b/plugin/dapp/lottery/types/lottery.go index a67075eebd..ad3f3fca15 100755 --- a/plugin/dapp/lottery/types/lottery.go +++ b/plugin/dapp/lottery/types/lottery.go @@ -23,12 +23,12 @@ func init() { types.RegExec(LotteryX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(LotteryX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(LotteryX, NewType(cfg)) } diff --git a/plugin/dapp/lottery/types/types.go b/plugin/dapp/lottery/types/types.go index 080ada3abf..a10ef7aa74 100755 --- a/plugin/dapp/lottery/types/types.go +++ b/plugin/dapp/lottery/types/types.go @@ -4,7 +4,7 @@ package types -//Lottery op +// Lottery op const ( LotteryActionCreate = 1 + iota LotteryActionBuy @@ -24,7 +24,7 @@ const ( LotteryX = "lottery" ) -//Lottery status +// Lottery status const ( LotteryCreated = 1 + iota LotteryPurchase diff --git a/plugin/dapp/mix/commands/mix.go b/plugin/dapp/mix/commands/mix.go index db3b1c62e4..58e2d03f4a 100644 --- a/plugin/dapp/mix/commands/mix.go +++ b/plugin/dapp/mix/commands/mix.go @@ -20,7 +20,7 @@ import ( "github.com/spf13/cobra" ) -//ParcCmd paracross cmd register +// ParcCmd paracross cmd register func MixCmd() *cobra.Command { cmd := &cobra.Command{ Use: "mix", @@ -957,14 +957,14 @@ func CreateDepositRawTxCmd() *cobra.Command { } func depositSecretCmdFlags(cmd *cobra.Command) { - cmd.Flags().StringP("receiver", "t", "", "receiver addrs,seperated by ','") + cmd.Flags().StringP("receiver", "t", "", "receiver addrs,separated by ','") cmd.MarkFlagRequired("receiver") cmd.Flags().StringP("return", "r", "", "return addr,optional") cmd.Flags().StringP("authorize", "a", "", "authorize addr,optional") - cmd.Flags().StringP("amount", "m", "", "amounts,seperated by ','") + cmd.Flags().StringP("amount", "m", "", "amounts,separated by ','") cmd.MarkFlagRequired("amount") cmd.Flags().StringP("symbol", "s", "BTY", "asset symbol,like BTY") @@ -1029,7 +1029,7 @@ func CreateTransferRawTxCmd() *cobra.Command { } func transferSecretCmdFlags(cmd *cobra.Command) { - cmd.Flags().StringP("noteHash", "n", "", "note hash to spend, seperate by ',' ") + cmd.Flags().StringP("noteHash", "n", "", "note hash to spend, separate by ',' ") cmd.MarkFlagRequired("noteHash") cmd.Flags().StringP("toAddr", "t", "", "transfer to addr, only one addr") diff --git a/plugin/dapp/mix/executor/committree.go b/plugin/dapp/mix/executor/committree.go index dab4361908..2eb5366154 100644 --- a/plugin/dapp/mix/executor/committree.go +++ b/plugin/dapp/mix/executor/committree.go @@ -10,9 +10,9 @@ import ( dbm "github.com/33cn/chain33/common/db" "github.com/33cn/chain33/types" + "github.com/33cn/plugin/plugin/crypto/legacymimc" "github.com/33cn/plugin/plugin/dapp/mix/executor/merkletree" mixTy "github.com/33cn/plugin/plugin/dapp/mix/types" - "github.com/33cn/plugin/plugin/crypto/legacymimc" "github.com/golang/protobuf/proto" "github.com/pkg/errors" ) @@ -93,7 +93,7 @@ func getArchiveRoots(db dbm.KV, exec, symbol string, seq uint64) (*mixTy.CommitT return getCommitTreeRoots(db, calcArchiveRootsKey(exec, symbol, seq)) } -//TODO seed config +// TODO seed config func getNewTree() *merkletree.Tree { return merkletree.New(legacymimc.NewMiMC(mixTy.MimcHashSeed)) } @@ -238,9 +238,9 @@ func restoreSubTrees(subTrees *mixTy.CommitSubTrees) (*merkletree.Tree, error) { } -//merkle树由子树构成,任何一个节点都是一个子树,如果一个子树高度不为0,则是一个高阶子树,高阶子树可以直接参与root计算,不需要再统计其叶子节点 -//高阶子树一定是一个完全子树,即左右叶子节点都存在,只有0阶子树不是完全子树,只有一个叶子 -//为了计算1024个叶子节点任何一个新节点n的roothash,需要累计前n-1个叶子节点,由于1024个叶子存取耗时,这里只保存最多10个高阶子树即可计算roothash +// merkle树由子树构成,任何一个节点都是一个子树,如果一个子树高度不为0,则是一个高阶子树,高阶子树可以直接参与root计算,不需要再统计其叶子节点 +// 高阶子树一定是一个完全子树,即左右叶子节点都存在,只有0阶子树不是完全子树,只有一个叶子 +// 为了计算1024个叶子节点任何一个新节点n的roothash,需要累计前n-1个叶子节点,由于1024个叶子存取耗时,这里只保存最多10个高阶子树即可计算roothash func joinSubTrees(status *mixTy.CommitTreeStatus, leaf []byte) ([]byte, error) { tree, err := restoreSubTrees(status.SubTrees) if err != nil { @@ -418,8 +418,8 @@ func getProveData(targetLeaf []byte, leaves [][]byte) (*mixTy.CommitTreeProve, e } -//1. 首先在当前tree查找 -//2. 如果提供了rootHash,则根据roothash+leaf查找,否则全局遍历查找 +// 1. 首先在当前tree查找 +// 2. 如果提供了rootHash,则根据roothash+leaf查找,否则全局遍历查找 func CalcTreeProve(db dbm.KV, exec, symbol, rootHash, leaf string) (*mixTy.CommitTreeProve, error) { if len(leaf) <= 0 { return nil, errors.Wrap(types.ErrInvalidParam, "leaf is null") diff --git a/plugin/dapp/mix/executor/committree_test.go b/plugin/dapp/mix/executor/committree_test.go index c704341362..45b9a00f0a 100644 --- a/plugin/dapp/mix/executor/committree_test.go +++ b/plugin/dapp/mix/executor/committree_test.go @@ -64,6 +64,6 @@ func TestGetProveData(t *testing.T) { for i, k := range proves { assert.Equal(t, k, ret.ProofSet[i]) } - assert.Equal(t, []uint32([]uint32{0, 1, 1}), ret.Helpers) + assert.Equal(t, []uint32{0, 1, 1}, ret.Helpers) } diff --git a/plugin/dapp/mix/executor/exec.go b/plugin/dapp/mix/executor/exec.go index f931ea4a34..29d035d735 100644 --- a/plugin/dapp/mix/executor/exec.go +++ b/plugin/dapp/mix/executor/exec.go @@ -11,7 +11,7 @@ import ( mixTy "github.com/33cn/plugin/plugin/dapp/mix/types" ) -//Exec_Commit consensus commit tx exec process +// Exec_Commit consensus commit tx exec process func (m *Mix) Exec_Config(payload *mixTy.MixConfigAction, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(m, tx) receipt, err := a.Config(payload) @@ -22,7 +22,7 @@ func (m *Mix) Exec_Config(payload *mixTy.MixConfigAction, tx *types.Transaction, return receipt, nil } -//Exec_Deposit ... +// Exec_Deposit ... func (m *Mix) Exec_Deposit(payload *mixTy.MixDepositAction, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(m, tx) receipt, err := a.Deposit(payload) @@ -33,7 +33,7 @@ func (m *Mix) Exec_Deposit(payload *mixTy.MixDepositAction, tx *types.Transactio return receipt, nil } -//Exec_Withdraw ... +// Exec_Withdraw ... func (m *Mix) Exec_Withdraw(payload *mixTy.MixWithdrawAction, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(m, tx) receipt, err := a.Withdraw(payload) diff --git a/plugin/dapp/mix/executor/exec_del_local.go b/plugin/dapp/mix/executor/exec_del_local.go index 0d00828751..243d801e82 100644 --- a/plugin/dapp/mix/executor/exec_del_local.go +++ b/plugin/dapp/mix/executor/exec_del_local.go @@ -9,17 +9,17 @@ import ( mixTy "github.com/33cn/plugin/plugin/dapp/mix/types" ) -//ExecLocal_Config asset withdraw local db process +// ExecLocal_Config asset withdraw local db process func (m *Mix) ExecDelLocal_Config(payload *mixTy.MixConfigAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return nil, nil } -//ExecLocal_Deposit asset withdraw local db process +// ExecLocal_Deposit asset withdraw local db process func (m *Mix) ExecDelLocal_Deposit(payload *mixTy.MixDepositAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return m.execAutoDelLocal(tx, receiptData) } -//ExecLocal_Withdraw asset withdraw local db process +// ExecLocal_Withdraw asset withdraw local db process func (m *Mix) ExecDelLocal_Withdraw(payload *mixTy.MixWithdrawAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return m.execAutoDelLocal(tx, receiptData) } @@ -29,7 +29,7 @@ func (m *Mix) ExecDelLocal_Transfer(payload *mixTy.MixTransferAction, tx *types. return m.execAutoDelLocal(tx, receiptData) } -//ExecLocal_Authorize asset withdraw local db process +// ExecLocal_Authorize asset withdraw local db process func (m *Mix) ExecDelLocal_Authorize(payload *mixTy.MixAuthorizeAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return m.execAutoDelLocal(tx, receiptData) } diff --git a/plugin/dapp/mix/executor/exec_local.go b/plugin/dapp/mix/executor/exec_local.go index 5f5e9db63a..e8938f3ba1 100644 --- a/plugin/dapp/mix/executor/exec_local.go +++ b/plugin/dapp/mix/executor/exec_local.go @@ -9,18 +9,18 @@ import ( mixTy "github.com/33cn/plugin/plugin/dapp/mix/types" ) -//ExecLocal_Config asset withdraw local db process +// ExecLocal_Config asset withdraw local db process func (m *Mix) ExecLocal_Config(payload *mixTy.MixConfigAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return nil, nil } -//ExecLocal_Deposit asset withdraw local db process +// ExecLocal_Deposit asset withdraw local db process func (m *Mix) ExecLocal_Deposit(payload *mixTy.MixDepositAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return m.execAutoLocalMix(tx, receiptData, index) } -//ExecLocal_Withdraw asset withdraw local db process +// ExecLocal_Withdraw asset withdraw local db process func (m *Mix) ExecLocal_Withdraw(payload *mixTy.MixWithdrawAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return m.execAutoLocalMix(tx, receiptData, index) } @@ -30,7 +30,7 @@ func (m *Mix) ExecLocal_Transfer(payload *mixTy.MixTransferAction, tx *types.Tra return m.execAutoLocalMix(tx, receiptData, index) } -//ExecLocal_Authorize asset withdraw local db process +// ExecLocal_Authorize asset withdraw local db process func (m *Mix) ExecLocal_Authorize(payload *mixTy.MixAuthorizeAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return m.execAutoLocalMix(tx, receiptData, index) } diff --git a/plugin/dapp/mix/executor/kv.go b/plugin/dapp/mix/executor/kv.go index 0091b02dc2..a99f83c22a 100644 --- a/plugin/dapp/mix/executor/kv.go +++ b/plugin/dapp/mix/executor/kv.go @@ -44,7 +44,7 @@ func setPrefix() { } -//support multi version verify parameter setting +// support multi version verify parameter setting func getVerifyKeysKey(ty int32) []byte { return []byte(fmt.Sprintf(verifyKeys+"%d", ty)) } diff --git a/plugin/dapp/mix/executor/merkletree/tree.go b/plugin/dapp/mix/executor/merkletree/tree.go index e2085225c7..1e03f7f561 100644 --- a/plugin/dapp/mix/executor/merkletree/tree.go +++ b/plugin/dapp/mix/executor/merkletree/tree.go @@ -64,7 +64,8 @@ func sum(h hash.Hash, data ...[]byte) []byte { // leafSum returns the hash created from data inserted to form a leaf. Leaf // sums are calculated using: -// Hash(0x00 || data) +// +// Hash(0x00 || data) func leafSum(h hash.Hash, data []byte) []byte { //return sum(h, leafHashPrefix, data) @@ -73,7 +74,8 @@ func leafSum(h hash.Hash, data []byte) []byte { // nodeSum returns the hash created from two sibling nodes being combined into // a parent node. Node sums are calculated using: -// Hash(0x01 || left sibling sum || right sibling sum) +// +// Hash(0x01 || left sibling sum || right sibling sum) func nodeSum(h hash.Hash, a, b []byte) []byte { //return sum(h, nodeHashPrefix, a, b) return sum(h, a, b) diff --git a/plugin/dapp/mix/executor/merkletree/tree_test.go b/plugin/dapp/mix/executor/merkletree/tree_test.go index a209854603..f0172a8d60 100644 --- a/plugin/dapp/mix/executor/merkletree/tree_test.go +++ b/plugin/dapp/mix/executor/merkletree/tree_test.go @@ -16,8 +16,8 @@ import ( "github.com/stretchr/testify/assert" - mixTy "github.com/33cn/plugin/plugin/dapp/mix/types" "github.com/33cn/plugin/plugin/crypto/legacymimc" + mixTy "github.com/33cn/plugin/plugin/dapp/mix/types" ) var h = legacymimc.NewMiMC("seed") diff --git a/plugin/dapp/mix/executor/merkletree/verify.go b/plugin/dapp/mix/executor/merkletree/verify.go index e664a70269..5f8b9ceca7 100644 --- a/plugin/dapp/mix/executor/merkletree/verify.go +++ b/plugin/dapp/mix/executor/merkletree/verify.go @@ -116,10 +116,7 @@ func VerifyProof(h hash.Hash, merkleRoot []byte, proofSet [][]byte, proofIndex u } // Compare our calculated Merkle root to the desired Merkle root. - if bytes.Equal(sum, merkleRoot) { - return true - } - return false + return bytes.Equal(sum, merkleRoot) } // GenerateProofHelper generates an array of 1 or 0 telling if during the proof verification diff --git a/plugin/dapp/mix/executor/mix.go b/plugin/dapp/mix/executor/mix.go index 3b1ece3ccb..fea8d726a0 100644 --- a/plugin/dapp/mix/executor/mix.go +++ b/plugin/dapp/mix/executor/mix.go @@ -22,20 +22,20 @@ type Mix struct { drivers.DriverBase } -//Init paracross exec register +// Init paracross exec register func Init(name string, cfg *types.Chain33Config, sub []byte) { drivers.Register(cfg, GetName(), newMix, cfg.GetDappFork(driverName, "Enable")) InitExecType() setPrefix() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Mix{})) } -//GetName return paracross name +// GetName return paracross name func GetName() string { return newMix().GetName() } diff --git a/plugin/dapp/mix/executor/mixtxtable.go b/plugin/dapp/mix/executor/mixtxtable.go index 818526b573..dede9db6c8 100644 --- a/plugin/dapp/mix/executor/mixtxtable.go +++ b/plugin/dapp/mix/executor/mixtxtable.go @@ -24,7 +24,7 @@ var txBoardOpt = &table.Option{ Index: []string{"height", "hash"}, } -//NewStageTable 新建表 +// NewStageTable 新建表 func NewMixTxTable(kvdb db.KV) *table.Table { rowmeta := NewMixTxRow() table, err := table.NewTable(rowmeta, kvdb, txBoardOpt) @@ -34,22 +34,22 @@ func NewMixTxTable(kvdb db.KV) *table.Table { return table } -//MixRow table meta 结构 +// MixRow table meta 结构 type MixTxRow struct { *mix.LocalMixTx } -//NewMixTxRow 新建一个meta 结构 +// NewMixTxRow 新建一个meta 结构 func NewMixTxRow() *MixTxRow { return &MixTxRow{LocalMixTx: &mix.LocalMixTx{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) func (r *MixTxRow) CreateRow() *table.Row { return &table.Row{Data: &mix.LocalMixTx{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *MixTxRow) SetPayload(data types.Message) error { if d, ok := data.(*mix.LocalMixTx); ok { r.LocalMixTx = d @@ -58,7 +58,7 @@ func (r *MixTxRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *MixTxRow) Get(key string) ([]byte, error) { switch key { case "txIndex": diff --git a/plugin/dapp/mix/executor/transfer.go b/plugin/dapp/mix/executor/transfer.go index 2cd3e9f79e..e184b25f8f 100644 --- a/plugin/dapp/mix/executor/transfer.go +++ b/plugin/dapp/mix/executor/transfer.go @@ -18,7 +18,6 @@ import ( /* 1. verify(zk-proof) 2. check if exist in authorize pool and nullifier pool - */ func transferInput(cfg *types.Chain33Config, db dbm.KV, execer, symbol string, proof *mixTy.ZkProofInfo) (*mixTy.TransferInputCircuit, error) { var input mixTy.TransferInputCircuit @@ -72,7 +71,6 @@ func transferInput(cfg *types.Chain33Config, db dbm.KV, execer, symbol string, p /* 1. verify(zk-proof) 2. check if exist in authorize pool and nullifier pool - */ func transferOutputVerify(cfg *types.Chain33Config, db dbm.KV, proof *mixTy.ZkProofInfo) (*mixTy.TransferOutputCircuit, error) { var input mixTy.TransferOutputCircuit @@ -195,7 +193,7 @@ func MixTransferInfoVerify(cfg *types.Chain33Config, db dbm.KV, transfer *mixTy. return inputs, outputs, nil } -//1. 如果 +// 1. 如果 func (a *action) processTransferFee(exec, symbol string) (*types.Receipt, error) { cfg := a.api.GetConfig() accoutDb, err := createAccount(cfg, exec, symbol, a.db) diff --git a/plugin/dapp/mix/executor/util.go b/plugin/dapp/mix/executor/util.go index 2d4af9bbbb..2210fab6e0 100644 --- a/plugin/dapp/mix/executor/util.go +++ b/plugin/dapp/mix/executor/util.go @@ -12,7 +12,7 @@ import ( "github.com/pkg/errors" ) -//考虑vk平滑切换的场景,允许有两个vk存在 +// 考虑vk平滑切换的场景,允许有两个vk存在 func zkProofVerify(db dbm.KV, proof *mixTy.ZkProofInfo, ty mixTy.VerifyType) error { keys, err := getVerifyKeys(db, int32(ty)) if err != nil { diff --git a/plugin/dapp/mix/rpc/rpc.go b/plugin/dapp/mix/rpc/rpc.go index c78d21c936..4c9bcf9c87 100644 --- a/plugin/dapp/mix/rpc/rpc.go +++ b/plugin/dapp/mix/rpc/rpc.go @@ -30,8 +30,7 @@ func (g *channelClient) GetRescanStatus(ctx context.Context, in *types.ReqNil) ( return data.(*types.ReqString), nil } -// -//// 扫描UTXO以及获取扫描UTXO后的状态 +// // 扫描UTXO以及获取扫描UTXO后的状态 func (g *channelClient) RescanNotes(ctx context.Context, in *types.ReqNil) (*types.ReqString, error) { data, err := g.ExecWalletFunc(mixTy.MixX, "RescanNotes", in) if err != nil { diff --git a/plugin/dapp/mix/types/authorize.go b/plugin/dapp/mix/types/authorize.go index 342399d153..843525681b 100644 --- a/plugin/dapp/mix/types/authorize.go +++ b/plugin/dapp/mix/types/authorize.go @@ -1,8 +1,8 @@ package types import ( - "github.com/consensys/gnark/frontend" "github.com/33cn/plugin/plugin/crypto/legacymimc" + "github.com/consensys/gnark/frontend" ) type AuthorizeCircuit struct { diff --git a/plugin/dapp/mix/types/cryptokey.pb.go b/plugin/dapp/mix/types/cryptokey.pb.go index c9a681fc0d..0c74cf6d9d 100644 --- a/plugin/dapp/mix/types/cryptokey.pb.go +++ b/plugin/dapp/mix/types/cryptokey.pb.go @@ -21,7 +21,7 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -//DH one time pubkey with secret +// DH one time pubkey with secret type DHSecret struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -77,7 +77,7 @@ func (x *DHSecret) GetSecret() string { return "" } -//Diff-Helman 加密group, for spender, returner, authorizer to decrypt +// Diff-Helman 加密group, for spender, returner, authorizer to decrypt type DHSecretGroup struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -256,8 +256,8 @@ func (x *EncryptSecretKeyPair) GetSecretPubKey() string { return "" } -//spend pair for note proof -//crypt pair for DH crypt/decrypt +// spend pair for note proof +// crypt pair for DH crypt/decrypt type AccountPrivacyKey struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/mix/types/deposit.go b/plugin/dapp/mix/types/deposit.go index 45bb6dfb5b..5b91b39071 100644 --- a/plugin/dapp/mix/types/deposit.go +++ b/plugin/dapp/mix/types/deposit.go @@ -1,11 +1,11 @@ package types import ( - "github.com/consensys/gnark/frontend" "github.com/33cn/plugin/plugin/crypto/legacymimc" + "github.com/consensys/gnark/frontend" ) -//spend commit hash the circuit implementing +// spend commit hash the circuit implementing type DepositCircuit struct { NoteHash frontend.Variable `gnark:",public"` Amount frontend.Variable `gnark:",public"` diff --git a/plugin/dapp/mix/types/merkletree.pb.go b/plugin/dapp/mix/types/merkletree.pb.go index 0b4a4f282d..8185fe3c90 100644 --- a/plugin/dapp/mix/types/merkletree.pb.go +++ b/plugin/dapp/mix/types/merkletree.pb.go @@ -21,7 +21,7 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -//子树用高度和hash描述,2^10=1024个叶子节点,子树高度不会超过10 +// 子树用高度和hash描述,2^10=1024个叶子节点,子树高度不会超过10 type CommitSubTree struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -77,7 +77,7 @@ func (x *CommitSubTree) GetHash() []byte { return nil } -//merkel tree由子树和叶子组成,三种场景:1,初始只一个叶子, 2,全是子树, 3,子树加一个叶子,不会有两个叶子,两个叶子一定构成子树 +// merkel tree由子树和叶子组成,三种场景:1,初始只一个叶子, 2,全是子树, 3,子树加一个叶子,不会有两个叶子,两个叶子一定构成子树 type CommitSubTrees struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -125,8 +125,8 @@ func (x *CommitSubTrees) GetSubTrees() []*CommitSubTree { return nil } -//描述当前commitTree的状态 -//一颗merkel树1024叶子,考虑数据库读取原因,每个叶子都会存到相应seq db,待第1024次时候归档,重新开始新的merkle树, +// 描述当前commitTree的状态 +// 一颗merkel树1024叶子,考虑数据库读取原因,每个叶子都会存到相应seq db,待第1024次时候归档,重新开始新的merkle树, type CommitTreeStatus struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/mix/types/mix.go b/plugin/dapp/mix/types/mix.go index 3796a24cf6..0dc6998e63 100644 --- a/plugin/dapp/mix/types/mix.go +++ b/plugin/dapp/mix/types/mix.go @@ -37,7 +37,7 @@ const ( TyLogMixConfigPaymentKey = 764 ) -//action type +// action type const ( MixActionConfig = iota MixActionDeposit @@ -46,7 +46,7 @@ const ( MixActionAuth ) -//circuits default file name +// circuits default file name const ( DepositPk = "circuit_deposit.pk" DepositVk = "circuit_deposit.vk" diff --git a/plugin/dapp/mix/types/mix.pb.go b/plugin/dapp/mix/types/mix.pb.go index b570ef63b7..220872128a 100644 --- a/plugin/dapp/mix/types/mix.pb.go +++ b/plugin/dapp/mix/types/mix.pb.go @@ -21,7 +21,7 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -//区分不同的验证电路 +// 区分不同的验证电路 type VerifyType int32 const ( @@ -445,8 +445,8 @@ func (x *TokenTxFeeAddrReq) GetAssetSymbol() string { return "" } -//config verify parameter for proof -//当前authPk=mimc_hash(prikey),没有X,Y值 +// config verify parameter for proof +// 当前authPk=mimc_hash(prikey),没有X,Y值 type MixConfigAction struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1081,7 +1081,7 @@ func (x *VerifyProofInfo) GetProof() *ZkProofInfo { return nil } -//nullifer 存在value +// nullifer 存在value type ExistValue struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/mix/types/mixwallet.pb.go b/plugin/dapp/mix/types/mixwallet.pb.go index 88c4a2fb5a..59112cd6e7 100644 --- a/plugin/dapp/mix/types/mixwallet.pb.go +++ b/plugin/dapp/mix/types/mixwallet.pb.go @@ -130,7 +130,7 @@ func (MixWalletRescanStatus) EnumDescriptor() ([]byte, []int) { return file_mixwallet_proto_rawDescGZIP(), []int{1} } -//支持同时存入多个地址,多个地址具有相同的returnAddr和AuthorizeAddr,如果不同,则单个来存 +// 支持同时存入多个地址,多个地址具有相同的returnAddr和AuthorizeAddr,如果不同,则单个来存 type DepositInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -202,7 +202,7 @@ func (x *DepositInfo) GetAmounts() string { return "" } -//钱包生成deposit tx +// 钱包生成deposit tx type DepositTxReq struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -321,7 +321,7 @@ func (x *DepositProofResp) GetSecrets() *DHSecretGroup { return nil } -//可withdraw 多个note +// 可withdraw 多个note type WithdrawTxReq struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -385,7 +385,7 @@ func (x *WithdrawTxReq) GetZkPath() string { return "" } -//只授权一个note,超过一个,toAddr不好设置 +// 只授权一个note,超过一个,toAddr不好设置 type AuthTxReq struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -661,7 +661,7 @@ func (x *CreateZkKeyFileReq) GetSavePath() string { return "" } -//加密了的input/output amount +// 加密了的input/output amount type ShieldAmount struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/mix/types/transferInput.go b/plugin/dapp/mix/types/transferInput.go index b1a0bdd05f..8282cc67a7 100644 --- a/plugin/dapp/mix/types/transferInput.go +++ b/plugin/dapp/mix/types/transferInput.go @@ -1,8 +1,8 @@ package types import ( - "github.com/consensys/gnark/frontend" "github.com/33cn/plugin/plugin/crypto/legacymimc" + "github.com/consensys/gnark/frontend" ) type TransferInputCircuit struct { diff --git a/plugin/dapp/mix/types/transferOutput.go b/plugin/dapp/mix/types/transferOutput.go index 6f17b13809..2173ce3a7c 100644 --- a/plugin/dapp/mix/types/transferOutput.go +++ b/plugin/dapp/mix/types/transferOutput.go @@ -1,8 +1,8 @@ package types import ( - "github.com/consensys/gnark/frontend" "github.com/33cn/plugin/plugin/crypto/legacymimc" + "github.com/consensys/gnark/frontend" ) type TransferOutputCircuit struct { diff --git a/plugin/dapp/mix/types/type.go b/plugin/dapp/mix/types/type.go index 31b5e42f9f..b3328987dc 100644 --- a/plugin/dapp/mix/types/type.go +++ b/plugin/dapp/mix/types/type.go @@ -27,13 +27,13 @@ func init() { } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(MixX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(MixX, NewType(cfg)) } diff --git a/plugin/dapp/mix/types/withdraw.go b/plugin/dapp/mix/types/withdraw.go index c53db8c5e8..6459fb5dc5 100644 --- a/plugin/dapp/mix/types/withdraw.go +++ b/plugin/dapp/mix/types/withdraw.go @@ -1,8 +1,8 @@ package types import ( - "github.com/consensys/gnark/frontend" "github.com/33cn/plugin/plugin/crypto/legacymimc" + "github.com/consensys/gnark/frontend" ) type WithdrawCircuit struct { diff --git a/plugin/dapp/mix/wallet/exec.go b/plugin/dapp/mix/wallet/exec.go index a5632f9e84..13203c2dbb 100644 --- a/plugin/dapp/mix/wallet/exec.go +++ b/plugin/dapp/mix/wallet/exec.go @@ -52,7 +52,7 @@ func (p *mixPolicy) On_GetRescanStatus(in *types.ReqNil) (types.Message, error) } -//重新扫描所有notes +// 重新扫描所有notes func (p *mixPolicy) On_RescanNotes(in *types.ReqNil) (types.Message, error) { err := p.tryRescanNotes() if err != nil { diff --git a/plugin/dapp/mix/wallet/mix.go b/plugin/dapp/mix/wallet/mix.go index 9efb40a733..272c410ef6 100644 --- a/plugin/dapp/mix/wallet/mix.go +++ b/plugin/dapp/mix/wallet/mix.go @@ -92,7 +92,7 @@ func (p *mixPolicy) savePrivacyPair(addr string) (*mixTy.WalletAddrPrivacy, erro return &mixTy.WalletAddrPrivacy{Privacy: newPrivacy, Addr: addr}, nil } -//查询钱包里面所有的地址对应的PrivacyKeys +// 查询钱包里面所有的地址对应的PrivacyKeys func (p *mixPolicy) getWalletPrivacyKeys() ([]*mixTy.WalletAddrPrivacy, error) { //通过Account前缀查找获取钱包中的所有账户信息 WalletAccStores, err := p.store.GetAccountByPrefix("Account") @@ -146,7 +146,7 @@ func (p *mixPolicy) tryRescanNotes() error { return nil } -//从localdb中把Mix合约的交易按升序都获取出来依次处理 +// 从localdb中把Mix合约的交易按升序都获取出来依次处理 func (p *mixPolicy) rescanNotes() { var txInfo mixTy.LocalMixTx i := 0 @@ -207,7 +207,6 @@ func (p *mixPolicy) rescanNotes() { } p.store.setRescanNoteStatus(int32(mixTy.MixWalletRescanStatus_FINISHED)) - return } func (p *mixPolicy) processPrivcyTxs(ReqHashes *types.ReqHashes) { diff --git a/plugin/dapp/mix/wallet/mixbizdb.go b/plugin/dapp/mix/wallet/mixbizdb.go index b8b02ad439..5cc4c5e2db 100644 --- a/plugin/dapp/mix/wallet/mixbizdb.go +++ b/plugin/dapp/mix/wallet/mixbizdb.go @@ -7,7 +7,6 @@ package wallet import ( "encoding/hex" - "github.com/33cn/chain33/common" commondb "github.com/33cn/chain33/common/db" @@ -18,7 +17,7 @@ import ( "github.com/pkg/errors" ) -//空的公钥字符为“0”,不是空,这里多设置了长度 +// 空的公钥字符为“0”,不是空,这里多设置了长度 const LENNULLKEY = 10 func (p *mixPolicy) execAutoLocalMix(tx *types.Transaction, receiptData *types.ReceiptData, index int, height int64) (*types.LocalDBSet, error) { diff --git a/plugin/dapp/mix/wallet/mixbiztable.go b/plugin/dapp/mix/wallet/mixbiztable.go index f93a4c018d..0d524c20bc 100644 --- a/plugin/dapp/mix/wallet/mixbiztable.go +++ b/plugin/dapp/mix/wallet/mixbiztable.go @@ -31,7 +31,7 @@ var boardOpt = &table.Option{ "owner_status"}, } -//NewStageTable 新建表 +// NewStageTable 新建表 func NewMixTable(kvdb db.KV) *table.Table { rowmeta := NewMixRow() table, err := table.NewTable(rowmeta, kvdb, boardOpt) @@ -41,22 +41,22 @@ func NewMixTable(kvdb db.KV) *table.Table { return table } -//MixRow table meta 结构 +// MixRow table meta 结构 type MixRow struct { *mix.WalletDbMixInfo } -//NewStageRow 新建一个meta 结构 +// NewStageRow 新建一个meta 结构 func NewMixRow() *MixRow { return &MixRow{WalletDbMixInfo: &mix.WalletDbMixInfo{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) func (r *MixRow) CreateRow() *table.Row { return &table.Row{Data: &mix.WalletDbMixInfo{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *MixRow) SetPayload(data types.Message) error { if d, ok := data.(*mix.WalletDbMixInfo); ok { r.WalletDbMixInfo = d @@ -65,7 +65,7 @@ func (r *MixRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *MixRow) Get(key string) ([]byte, error) { switch key { case "heightindex": diff --git a/plugin/dapp/mix/wallet/mixstore.go b/plugin/dapp/mix/wallet/mixstore.go index f189b2ef98..dc2bc55bb8 100644 --- a/plugin/dapp/mix/wallet/mixstore.go +++ b/plugin/dapp/mix/wallet/mixstore.go @@ -54,10 +54,7 @@ func (store *mixStore) enablePrivacy() { func (store *mixStore) getPrivacyEnable() bool { _, err := store.Get(calcMixPrivacyEnable()) - if err != nil { - return false - } - return true + return err == nil } func (store *mixStore) setRescanNoteStatus(status int32) { @@ -82,7 +79,7 @@ func (store *mixStore) getRescanNoteStatus() int32 { return mixTy.MixWalletRescanStatus_value[string(v)] } -//AddRollbackKV add rollback kv +// AddRollbackKV add rollback kv func (d *mixStore) AddRollbackKV(tx *types.Transaction, execer []byte, kvs []*types.KeyValue) []*types.KeyValue { k := types.CalcRollbackKey(types.GetRealExecName(execer), tx.Hash()) kvc := system.NewKVCreator(d.GetDB(), types.CalcLocalPrefix(execer), k) @@ -91,7 +88,7 @@ func (d *mixStore) AddRollbackKV(tx *types.Transaction, execer []byte, kvs []*ty return kvc.KVList() } -//DelRollbackKV del rollback kv when exec_del_local +// DelRollbackKV del rollback kv when exec_del_local func (d *mixStore) DelRollbackKV(tx *types.Transaction, execer []byte) ([]*types.KeyValue, error) { krollback := types.CalcRollbackKey(types.GetRealExecName(execer), tx.Hash()) kvc := system.NewKVCreator(d.GetDB(), types.CalcLocalPrefix(execer), krollback) diff --git a/plugin/dapp/mix/wallet/txtransfer.go b/plugin/dapp/mix/wallet/txtransfer.go index c753873ff9..48d095f608 100644 --- a/plugin/dapp/mix/wallet/txtransfer.go +++ b/plugin/dapp/mix/wallet/txtransfer.go @@ -7,7 +7,6 @@ package wallet import ( "path/filepath" - "strconv" "strings" @@ -94,7 +93,7 @@ func (p *mixPolicy) getTransferOutput(exec, symbol string, req *mixTy.DepositInf } -//input = output+找零+交易费 +// input = output+找零+交易费 func getShieldValue(inputAmounts []uint64, outAmount, change, minTxFee uint64, pointHX, pointHY string) (*mixTy.ShieldAmountRst, error) { var sum uint64 for _, i := range inputAmounts { diff --git a/plugin/dapp/mix/wallet/txwithdraw.go b/plugin/dapp/mix/wallet/txwithdraw.go index fcad7c5473..28e38e413c 100644 --- a/plugin/dapp/mix/wallet/txwithdraw.go +++ b/plugin/dapp/mix/wallet/txwithdraw.go @@ -8,7 +8,6 @@ import ( "path/filepath" "strings" - "github.com/33cn/chain33/common/address" "github.com/33cn/chain33/types" "github.com/pkg/errors" diff --git a/plugin/dapp/mix/wallet/util.go b/plugin/dapp/mix/wallet/util.go index c03619dec2..b298721ad0 100644 --- a/plugin/dapp/mix/wallet/util.go +++ b/plugin/dapp/mix/wallet/util.go @@ -28,7 +28,7 @@ import ( "github.com/33cn/plugin/plugin/dapp/mix/executor/zksnark" ) -//产生随机秘钥和receivingPk对data DH加密,返回随机秘钥的公钥 +// 产生随机秘钥和receivingPk对data DH加密,返回随机秘钥的公钥 func encryptSecretData(req *mixTy.EncryptSecretData) (*mixTy.DHSecret, error) { secret, err := common.FromHex(req.Secret) if err != nil { @@ -172,7 +172,7 @@ func getCircuitKeyFileName(circuitTy mixTy.VerifyType) (string, string, error) { } } -//文件内容存储的是hex string,读的时候直接转换为string即可 +// 文件内容存储的是hex string,读的时候直接转换为string即可 func readZkKeyFile(path string) (string, error) { f, err := os.Open(path) if err != nil { diff --git a/plugin/dapp/mix/wallet/util_test.go b/plugin/dapp/mix/wallet/util_test.go index bd4427e878..cda4944c58 100644 --- a/plugin/dapp/mix/wallet/util_test.go +++ b/plugin/dapp/mix/wallet/util_test.go @@ -3,7 +3,6 @@ package wallet import ( "testing" - "github.com/33cn/chain33/common" mixTy "github.com/33cn/plugin/plugin/dapp/mix/types" "github.com/stretchr/testify/assert" diff --git a/plugin/dapp/multisig/commands/multisig.go b/plugin/dapp/multisig/commands/multisig.go index 5caf102d21..121dbf6cb6 100644 --- a/plugin/dapp/multisig/commands/multisig.go +++ b/plugin/dapp/multisig/commands/multisig.go @@ -21,7 +21,7 @@ import ( "github.com/spf13/cobra" ) -//MultiSigCmd : +// MultiSigCmd : func MultiSigCmd() *cobra.Command { cmd := &cobra.Command{ Use: "multisig", @@ -36,7 +36,7 @@ func MultiSigCmd() *cobra.Command { return cmd } -//MultiSigAccountCmd :account相关的命令 +// MultiSigAccountCmd :account相关的命令 func MultiSigAccountCmd() *cobra.Command { cmd := &cobra.Command{ Use: "account", @@ -58,7 +58,7 @@ func MultiSigAccountCmd() *cobra.Command { return cmd } -//MultiSigOwnerCmd : owner相关的命令 +// MultiSigOwnerCmd : owner相关的命令 func MultiSigOwnerCmd() *cobra.Command { cmd := &cobra.Command{ Use: "owner", @@ -74,7 +74,7 @@ func MultiSigOwnerCmd() *cobra.Command { return cmd } -//MultiSigTxCmd : tx交易相关的命令 +// MultiSigTxCmd : tx交易相关的命令 func MultiSigTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "tx", @@ -630,7 +630,7 @@ func createMultiSigAccTransferOut(cmd *cobra.Command, args []string) { ctx.RunWithoutMarshal() } -//GetMultiSigAccCountCmd 获取已经创建的多重签名账户数量 +// GetMultiSigAccCountCmd 获取已经创建的多重签名账户数量 func GetMultiSigAccCountCmd() *cobra.Command { cmd := &cobra.Command{ Use: "count", @@ -655,7 +655,7 @@ func getMultiSigAccCount(cmd *cobra.Command, args []string) { ctx.Run() } -//GetMultiSigAccountsCmd 获取已经创建的多重签名账户地址,通过转入的index +// GetMultiSigAccountsCmd 获取已经创建的多重签名账户地址,通过转入的index func GetMultiSigAccountsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "address", @@ -701,7 +701,7 @@ func getMultiSigAccounts(cmd *cobra.Command, args []string) { ctx.Run() } -//GetMultiSigAccountInfoCmd 获取已经创建的多重签名账户信息 +// GetMultiSigAccountInfoCmd 获取已经创建的多重签名账户信息 func GetMultiSigAccountInfoCmd() *cobra.Command { cmd := &cobra.Command{ Use: "info", @@ -772,7 +772,7 @@ func parseAccInfo(view ...interface{}) (interface{}, error) { return result, nil } -//GetMultiSigAccTxCountCmd 获取多重签名账户上的tx交易数量 +// GetMultiSigAccTxCountCmd 获取多重签名账户上的tx交易数量 func GetMultiSigAccTxCountCmd() *cobra.Command { cmd := &cobra.Command{ Use: "count", @@ -807,7 +807,7 @@ func getMultiSigAccTxCount(cmd *cobra.Command, args []string) { ctx.Run() } -//GetMultiSigTxidsCmd 获取多重签名账户上的tx交易数量 +// GetMultiSigTxidsCmd 获取多重签名账户上的tx交易数量 func GetMultiSigTxidsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "txids", @@ -878,7 +878,7 @@ func getMultiSigTxids(cmd *cobra.Command, args []string) { ctx.Run() } -//GetMultiSigTxInfoCmd 获取已经创建的多重签名账户的交易信息 +// GetMultiSigTxInfoCmd 获取已经创建的多重签名账户的交易信息 func GetMultiSigTxInfoCmd() *cobra.Command { cmd := &cobra.Command{ Use: "info", @@ -918,7 +918,7 @@ func getMultiSigTxInfo(cmd *cobra.Command, args []string) { ctx.Run() } -//GetMultiSigTxConfirmedWeightCmd 获取交易已经被确认的总权重 +// GetMultiSigTxConfirmedWeightCmd 获取交易已经被确认的总权重 func GetMultiSigTxConfirmedWeightCmd() *cobra.Command { cmd := &cobra.Command{ Use: "confirmed_weight", @@ -958,7 +958,7 @@ func getGetMultiSigTxConfirmedWeight(cmd *cobra.Command, args []string) { ctx.Run() } -//GetMultiSigAccUnSpentTodayCmd 获取多重签名账户今日免多重签名的余额 +// GetMultiSigAccUnSpentTodayCmd 获取多重签名账户今日免多重签名的余额 func GetMultiSigAccUnSpentTodayCmd() *cobra.Command { cmd := &cobra.Command{ Use: "unspent", @@ -1037,7 +1037,7 @@ func parseUnSpentToday(view ...interface{}) (interface{}, error) { return result, nil } -//GetMultiSigAccAssetsCmd 获取多重签名账户上的资产信息 +// GetMultiSigAccAssetsCmd 获取多重签名账户上的资产信息 func GetMultiSigAccAssetsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "assets", @@ -1122,7 +1122,7 @@ func parseAccAssets(view ...interface{}) (interface{}, error) { return result, nil } -//GetMultiSigAccAllAddressCmd 获取指定地址创建的所有多重签名账户 +// GetMultiSigAccAllAddressCmd 获取指定地址创建的所有多重签名账户 func GetMultiSigAccAllAddressCmd() *cobra.Command { cmd := &cobra.Command{ Use: "creator", @@ -1162,7 +1162,7 @@ func isValidDailylimit(dailylimit float64) error { return nil } -//GetMultiSigAccByOwnerCmd 获取指定地址拥有的所有多重签名账户 +// GetMultiSigAccByOwnerCmd 获取指定地址拥有的所有多重签名账户 func GetMultiSigAccByOwnerCmd() *cobra.Command { cmd := &cobra.Command{ Use: "owner", diff --git a/plugin/dapp/multisig/executor/exec.go b/plugin/dapp/multisig/executor/exec.go index 0b74de0bc9..d5c4f7dff4 100644 --- a/plugin/dapp/multisig/executor/exec.go +++ b/plugin/dapp/multisig/executor/exec.go @@ -9,37 +9,37 @@ import ( mty "github.com/33cn/plugin/plugin/dapp/multisig/types" ) -//Exec_MultiSigAccCreate 创建多重签名账户 +// Exec_MultiSigAccCreate 创建多重签名账户 func (m *MultiSig) Exec_MultiSigAccCreate(payload *mty.MultiSigAccCreate, tx *types.Transaction, index int) (*types.Receipt, error) { action := newAction(m, tx, int32(index)) return action.MultiSigAccCreate(payload) } -//Exec_MultiSigOwnerOperate 多重签名账户owner属性的修改:owner的add/del/replace等 +// Exec_MultiSigOwnerOperate 多重签名账户owner属性的修改:owner的add/del/replace等 func (m *MultiSig) Exec_MultiSigOwnerOperate(payload *mty.MultiSigOwnerOperate, tx *types.Transaction, index int) (*types.Receipt, error) { action := newAction(m, tx, int32(index)) return action.MultiSigOwnerOperate(payload) } -//Exec_MultiSigAccOperate 多重签名账户属性的修改:weight权重以及每日限额的修改 +// Exec_MultiSigAccOperate 多重签名账户属性的修改:weight权重以及每日限额的修改 func (m *MultiSig) Exec_MultiSigAccOperate(payload *mty.MultiSigAccOperate, tx *types.Transaction, index int) (*types.Receipt, error) { action := newAction(m, tx, int32(index)) return action.MultiSigAccOperate(payload) } -//Exec_MultiSigConfirmTx 多重签名账户上交易的确认和撤销 +// Exec_MultiSigConfirmTx 多重签名账户上交易的确认和撤销 func (m *MultiSig) Exec_MultiSigConfirmTx(payload *mty.MultiSigConfirmTx, tx *types.Transaction, index int) (*types.Receipt, error) { action := newAction(m, tx, int32(index)) return action.MultiSigConfirmTx(payload) } -//Exec_MultiSigExecTransferTo 合约中外部账户转账到多重签名账户,Addr --->multiSigAddr +// Exec_MultiSigExecTransferTo 合约中外部账户转账到多重签名账户,Addr --->multiSigAddr func (m *MultiSig) Exec_MultiSigExecTransferTo(payload *mty.MultiSigExecTransferTo, tx *types.Transaction, index int) (*types.Receipt, error) { action := newAction(m, tx, int32(index)) return action.MultiSigExecTransferTo(payload) } -//Exec_MultiSigExecTransferFrom 合约中多重签名账户转账到外部账户,multiSigAddr--->Addr +// Exec_MultiSigExecTransferFrom 合约中多重签名账户转账到外部账户,multiSigAddr--->Addr func (m *MultiSig) Exec_MultiSigExecTransferFrom(payload *mty.MultiSigExecTransferFrom, tx *types.Transaction, index int) (*types.Receipt, error) { action := newAction(m, tx, int32(index)) return action.MultiSigExecTransferFrom(payload) diff --git a/plugin/dapp/multisig/executor/exec_del_local.go b/plugin/dapp/multisig/executor/exec_del_local.go index c6e0dc0bc8..86454cbc37 100644 --- a/plugin/dapp/multisig/executor/exec_del_local.go +++ b/plugin/dapp/multisig/executor/exec_del_local.go @@ -9,7 +9,7 @@ import ( mty "github.com/33cn/plugin/plugin/dapp/multisig/types" ) -//ExecDelLocal_MultiSigAccCreate 创建多重签名账户,根据payload和receiptData信息获取相关信息并保存到db中 +// ExecDelLocal_MultiSigAccCreate 创建多重签名账户,根据payload和receiptData信息获取相关信息并保存到db中 func (m *MultiSig) ExecDelLocal_MultiSigAccCreate(payload *mty.MultiSigAccCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if receiptData.GetTy() != types.ExecOk { return &types.LocalDBSet{}, nil @@ -22,7 +22,7 @@ func (m *MultiSig) ExecDelLocal_MultiSigAccCreate(payload *mty.MultiSigAccCreate return &types.LocalDBSet{KV: kv}, nil } -//ExecDelLocal_MultiSigOwnerOperate 多重签名账户owner属性的修改:owner的add/del/replace/modify等 +// ExecDelLocal_MultiSigOwnerOperate 多重签名账户owner属性的修改:owner的add/del/replace/modify等 func (m *MultiSig) ExecDelLocal_MultiSigOwnerOperate(payload *mty.MultiSigOwnerOperate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if receiptData.GetTy() != types.ExecOk { return &types.LocalDBSet{}, nil @@ -35,7 +35,7 @@ func (m *MultiSig) ExecDelLocal_MultiSigOwnerOperate(payload *mty.MultiSigOwnerO return &types.LocalDBSet{KV: kv}, nil } -//ExecDelLocal_MultiSigAccOperate 多重签名账户属性的修改:weight权重以及每日限额的修改 +// ExecDelLocal_MultiSigAccOperate 多重签名账户属性的修改:weight权重以及每日限额的修改 func (m *MultiSig) ExecDelLocal_MultiSigAccOperate(payload *mty.MultiSigAccOperate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if receiptData.GetTy() != types.ExecOk { return &types.LocalDBSet{}, nil @@ -48,7 +48,7 @@ func (m *MultiSig) ExecDelLocal_MultiSigAccOperate(payload *mty.MultiSigAccOpera return &types.LocalDBSet{KV: kv}, nil } -//ExecDelLocal_MultiSigConfirmTx 多重签名账户上交易的确认和撤销 +// ExecDelLocal_MultiSigConfirmTx 多重签名账户上交易的确认和撤销 func (m *MultiSig) ExecDelLocal_MultiSigConfirmTx(payload *mty.MultiSigConfirmTx, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if receiptData.GetTy() != types.ExecOk { return &types.LocalDBSet{}, nil @@ -61,7 +61,7 @@ func (m *MultiSig) ExecDelLocal_MultiSigConfirmTx(payload *mty.MultiSigConfirmTx return &types.LocalDBSet{KV: kv}, nil } -//ExecDelLocal_MultiSigExecTransferTo 合约中外部账户转账到多重签名账户,Addr --->multiSigAddr +// ExecDelLocal_MultiSigExecTransferTo 合约中外部账户转账到多重签名账户,Addr --->multiSigAddr func (m *MultiSig) ExecDelLocal_MultiSigExecTransferTo(payload *mty.MultiSigExecTransferTo, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if receiptData.GetTy() != types.ExecOk { return &types.LocalDBSet{}, nil @@ -74,7 +74,7 @@ func (m *MultiSig) ExecDelLocal_MultiSigExecTransferTo(payload *mty.MultiSigExec return &types.LocalDBSet{KV: kv}, nil } -//ExecDelLocal_MultiSigExecTransferFrom 合约中多重签名账户转账到外部账户,multiSigAddr--->Addr +// ExecDelLocal_MultiSigExecTransferFrom 合约中多重签名账户转账到外部账户,multiSigAddr--->Addr func (m *MultiSig) ExecDelLocal_MultiSigExecTransferFrom(payload *mty.MultiSigExecTransferFrom, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if receiptData.GetTy() != types.ExecOk { return &types.LocalDBSet{}, nil diff --git a/plugin/dapp/multisig/executor/exec_local.go b/plugin/dapp/multisig/executor/exec_local.go index 2dca575e3d..42640db359 100644 --- a/plugin/dapp/multisig/executor/exec_local.go +++ b/plugin/dapp/multisig/executor/exec_local.go @@ -9,7 +9,7 @@ import ( mty "github.com/33cn/plugin/plugin/dapp/multisig/types" ) -//ExecLocal_MultiSigAccCreate 创建多重签名账户,根据payload和receiptData信息获取相关信息并保存到db中 +// ExecLocal_MultiSigAccCreate 创建多重签名账户,根据payload和receiptData信息获取相关信息并保存到db中 func (m *MultiSig) ExecLocal_MultiSigAccCreate(payload *mty.MultiSigAccCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if receiptData.GetTy() != types.ExecOk { return &types.LocalDBSet{}, nil @@ -23,7 +23,7 @@ func (m *MultiSig) ExecLocal_MultiSigAccCreate(payload *mty.MultiSigAccCreate, t return &types.LocalDBSet{KV: kv}, nil } -//ExecLocal_MultiSigOwnerOperate 多重签名账户owner属性的修改:owner的add/del/replace/modify等 +// ExecLocal_MultiSigOwnerOperate 多重签名账户owner属性的修改:owner的add/del/replace/modify等 func (m *MultiSig) ExecLocal_MultiSigOwnerOperate(payload *mty.MultiSigOwnerOperate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if receiptData.GetTy() != types.ExecOk { return &types.LocalDBSet{}, nil @@ -37,7 +37,7 @@ func (m *MultiSig) ExecLocal_MultiSigOwnerOperate(payload *mty.MultiSigOwnerOper return &types.LocalDBSet{KV: kv}, nil } -//ExecLocal_MultiSigAccOperate 多重签名账户属性的修改:weight权重以及每日限额的修改 +// ExecLocal_MultiSigAccOperate 多重签名账户属性的修改:weight权重以及每日限额的修改 func (m *MultiSig) ExecLocal_MultiSigAccOperate(payload *mty.MultiSigAccOperate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if receiptData.GetTy() != types.ExecOk { return &types.LocalDBSet{}, nil @@ -50,7 +50,7 @@ func (m *MultiSig) ExecLocal_MultiSigAccOperate(payload *mty.MultiSigAccOperate, return &types.LocalDBSet{KV: kv}, nil } -//ExecLocal_MultiSigConfirmTx 多重签名账户上交易的确认和撤销 +// ExecLocal_MultiSigConfirmTx 多重签名账户上交易的确认和撤销 func (m *MultiSig) ExecLocal_MultiSigConfirmTx(payload *mty.MultiSigConfirmTx, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if receiptData.GetTy() != types.ExecOk { return &types.LocalDBSet{}, nil @@ -64,7 +64,7 @@ func (m *MultiSig) ExecLocal_MultiSigConfirmTx(payload *mty.MultiSigConfirmTx, t return &types.LocalDBSet{KV: kv}, nil } -//ExecLocal_MultiSigExecTransferTo 合约中外部账户转账到多重签名账户,Addr --->multiSigAddr +// ExecLocal_MultiSigExecTransferTo 合约中外部账户转账到多重签名账户,Addr --->multiSigAddr func (m *MultiSig) ExecLocal_MultiSigExecTransferTo(payload *mty.MultiSigExecTransferTo, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if receiptData.GetTy() != types.ExecOk { return &types.LocalDBSet{}, nil @@ -78,7 +78,7 @@ func (m *MultiSig) ExecLocal_MultiSigExecTransferTo(payload *mty.MultiSigExecTra return &types.LocalDBSet{KV: kv}, nil } -//ExecLocal_MultiSigExecTransferFrom 合约中多重签名账户转账到外部账户,multiSigAddr--->Addr +// ExecLocal_MultiSigExecTransferFrom 合约中多重签名账户转账到外部账户,multiSigAddr--->Addr func (m *MultiSig) ExecLocal_MultiSigExecTransferFrom(payload *mty.MultiSigExecTransferFrom, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if receiptData.GetTy() != types.ExecOk { return &types.LocalDBSet{}, nil diff --git a/plugin/dapp/multisig/executor/exec_test.go b/plugin/dapp/multisig/executor/exec_test.go index 7d1a328d5b..2f0f7d738e 100644 --- a/plugin/dapp/multisig/executor/exec_test.go +++ b/plugin/dapp/multisig/executor/exec_test.go @@ -66,7 +66,7 @@ func init() { Init(mty.MultiSigX, chainTestCfg, nil) } -//创建一个多重签名的账户 +// 创建一个多重签名的账户 func TestMultiSigAccCreate(t *testing.T) { total := int64(100000) @@ -470,7 +470,7 @@ func testMultiSigOwnerReplace(t *testing.T, driver drivers.Driver, env execEnv, assert.Equal(t, int(ty), mty.TyLogMultiSigTx) } -//account 操作测试 +// account 操作测试 func testMultiSigAccWeightModify(t *testing.T, driver drivers.Driver, env execEnv, multiSigAddr string) { params := &mty.MultiSigAccOperate{ MultiSigAccAddr: multiSigAddr, @@ -613,12 +613,12 @@ func testMultiSigAccDailyLimitModify(t *testing.T, driver drivers.Driver, env ex } -//account 操作测试 -//当前账户的信息,txcount:6 Requiredweight:4 -//ownerAddr:"1JRNjdEqp4LJ5fqycUBm9ayCKSeeskgMKR" weight:2 -//ownerAddr:"1MCftFynyvG2F4ED5mdHYgziDxx6vDrScs" weight:10 ] -//[symbol:"bty" execer:"coins" dailyLimit:10 ] -//6 +// account 操作测试 +// 当前账户的信息,txcount:6 Requiredweight:4 +// ownerAddr:"1JRNjdEqp4LJ5fqycUBm9ayCKSeeskgMKR" weight:2 +// ownerAddr:"1MCftFynyvG2F4ED5mdHYgziDxx6vDrScs" weight:10 ] +// [symbol:"bty" execer:"coins" dailyLimit:10 ] +// 6 // 4} func testMultiSigAccConfirmTx(t *testing.T, driver drivers.Driver, env execEnv, api *apimock.QueueProtocolAPI, multiSigAddr string) { //首先创建一个修改Requiredweight权重的交易。由AddrB提交此交易,权限不够交易不被执行。 @@ -767,7 +767,7 @@ func testMultiSigAccConfirmTx(t *testing.T, driver drivers.Driver, env execEnv, } -//合约内转账到多重签名账户 +// 合约内转账到多重签名账户 func testMultiSigAccExecTransferTo(t *testing.T, driver drivers.Driver, env execEnv, multiSigAddr string) { params := &mty.MultiSigExecTransferTo{ Symbol: Symbol, @@ -839,7 +839,7 @@ func testMultiSigAccExecTransferTo(t *testing.T, driver drivers.Driver, env exec } -//合约内转账到多重签名账户 +// 合约内转账到多重签名账户 func testMultiSigAccExecTransferFrom(t *testing.T, driver drivers.Driver, env execEnv, multiSigAddr string) { params := &mty.MultiSigExecTransferFrom{ Symbol: Symbol, diff --git a/plugin/dapp/multisig/executor/kv.go b/plugin/dapp/multisig/executor/kv.go index eb6f283e08..8e3c7c9218 100644 --- a/plugin/dapp/multisig/executor/kv.go +++ b/plugin/dapp/multisig/executor/kv.go @@ -10,7 +10,7 @@ import ( "github.com/33cn/chain33/common/address" ) -//数据库存储格式key +// 数据库存储格式key const ( //MultiSigPrefix statedb中账户和交易的存储格式 MultiSigPrefix = "mavl-multisig-" @@ -26,12 +26,12 @@ const ( MultiSigAccCreate = "create" ) -//statedb中账户和交易的存储格式 +// statedb中账户和交易的存储格式 func calcMultiSigAccountKey(multiSigAccAddr string) (key []byte) { return []byte(fmt.Sprintf(MultiSigPrefix+"%s", address.FormatAddrKey(multiSigAccAddr))) } -//存储格式:"mavl-multisig-tx-accaddr-000000000000" +// 存储格式:"mavl-multisig-tx-accaddr-000000000000" func calcMultiSigAccTxKey(multiSigAccAddr string, txid uint64) (key []byte) { txstr := fmt.Sprintf("%018d", txid) return []byte(fmt.Sprintf(MultiSigTxPrefix+"%s-%s", address.FormatAddrKey(multiSigAccAddr), txstr)) @@ -39,43 +39,44 @@ func calcMultiSigAccTxKey(multiSigAccAddr string, txid uint64) (key []byte) { //localdb中账户相关的存储格式 -//记录创建的账户数量,key:Msac value:count。 +// 记录创建的账户数量,key:Msac value:count。 func calcMultiSigAccCountKey() []byte { return []byte(fmt.Sprintf(MultiSigLocalPrefix+"%s", MultiSigAccCount)) } -//存储所有的MultiSig账户地址:按顺序存储方便以后分页查找: key:Ms:allacc:index,value:accaddr +// 存储所有的MultiSig账户地址:按顺序存储方便以后分页查找: key:Ms:allacc:index,value:accaddr func calcMultiSigAllAcc(accindex int64) (key []byte) { accstr := fmt.Sprintf("%018d", accindex) return []byte(fmt.Sprintf(MultiSigLocalPrefix+"%s-%s", MultiSigAllAcc, accstr)) } -//记录指定账号地址的信息value:MultiSig。key:Ms:acc +// 记录指定账号地址的信息value:MultiSig。key:Ms:acc func calcMultiSigAcc(addr string) (key []byte) { return []byte(fmt.Sprintf(MultiSigLocalPrefix+"%s-%s", MultiSigAcc, address.FormatAddrKey(addr))) } -//记录某个地址创建的所有多重签名账户。key:Ms:create:createAddr,value:[]string。 +// 记录某个地址创建的所有多重签名账户。key:Ms:create:createAddr,value:[]string。 func calcMultiSigAccCreateAddr(createAddr string) (key []byte) { return []byte(fmt.Sprintf(MultiSigLocalPrefix+"%s:-%s", MultiSigAccCreate, address.FormatAddrKey(createAddr))) } //localdb中账户相关的存储格式 -//记录指定账号地址的信息key:Ms:tx:addr:txid value:MultiSigTx。 +// 记录指定账号地址的信息key:Ms:tx:addr:txid value:MultiSigTx。 func calcMultiSigAccTx(addr string, txid uint64) (key []byte) { accstr := fmt.Sprintf("%018d", txid) return []byte(fmt.Sprintf(MultiSigLocalPrefix+"%s-%s-%s", MultiSigTx, address.FormatAddrKey(addr), accstr)) } -//可以通过前缀查找获取指定账户上收到的所有资产数量 -//MultiSig合约中账户收到指定资产的计数key:Ms:assets:addr:execname:symbol value:AccountAssets。 -//message AccountAssets { -// string multiSigAddr = 1; -// string execer = 2; -// string symbol = 3; -// int64 amount = 4; +// 可以通过前缀查找获取指定账户上收到的所有资产数量 +// MultiSig合约中账户收到指定资产的计数key:Ms:assets:addr:execname:symbol value:AccountAssets。 +// +// message AccountAssets { +// string multiSigAddr = 1; +// string execer = 2; +// string symbol = 3; +// int64 amount = 4; func calcAddrRecvAmountKey(addr, execname, symbol string) []byte { return []byte(fmt.Sprintf(MultiSigLocalPrefix+"%s-%s-%s-%s", MultiSigRecvAssets, address.FormatAddrKey(addr), execname, symbol)) } diff --git a/plugin/dapp/multisig/executor/multisig.go b/plugin/dapp/multisig/executor/multisig.go index 9bf5fb0319..7946267953 100644 --- a/plugin/dapp/multisig/executor/multisig.go +++ b/plugin/dapp/multisig/executor/multisig.go @@ -40,7 +40,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&MultiSig{})) @@ -247,7 +247,7 @@ func checkAccountOperateTx(ato *mty.MultiSigAccOperate, multiSignDriver address. return nil } -//多重签名交易的Receipt处理 +// 多重签名交易的Receipt处理 func (m *MultiSig) execLocalMultiSigReceipt(receiptData *types.ReceiptData, tx *types.Transaction, addOrRollback bool) ([]*types.KeyValue, error) { var set []*types.KeyValue for _, log := range receiptData.Logs { @@ -393,7 +393,7 @@ func (m *MultiSig) execLocalMultiSigReceipt(receiptData *types.ReceiptData, tx * return set, nil } -//转账交易to地址收币数量更新,Submit直接解析tx。Confirm需要解析对应txid的交易信息 +// 转账交易to地址收币数量更新,Submit直接解析tx。Confirm需要解析对应txid的交易信息 func (m *MultiSig) saveMultiSigTransfer(tx *types.Transaction, SubmitOrConfirm, addOrRollback bool) ([]*types.KeyValue, error) { var set []*types.KeyValue //执行成功解析GetPayload信息 @@ -463,7 +463,7 @@ func (m *MultiSig) saveMultiSigTransfer(tx *types.Transaction, SubmitOrConfirm, return set, nil } -//localdb Receipt相关消息的处理。需要区分执行的是add/Rollback +// localdb Receipt相关消息的处理。需要区分执行的是add/Rollback func (m *MultiSig) saveMultiSigAccCreate(multiSig *mty.MultiSig, addOrRollback bool) ([]*types.KeyValue, error) { multiSigAddr := multiSig.MultiSigAddr //增加一个多重签名账户信息到localdb中,第一次增加时账户在local中应该是不存在的。如果存在就返回错误 @@ -518,7 +518,7 @@ func (m *MultiSig) saveMultiSigAccCreate(multiSig *mty.MultiSig, addOrRollback b return kvs, nil } -//账户owner的add/del操作.需要区分add/del 交易 +// 账户owner的add/del操作.需要区分add/del 交易 func (m *MultiSig) saveMultiSigOwnerAddOrDel(ownerOp mty.ReceiptOwnerAddOrDel, addOrRollback bool) ([]*types.KeyValue, error) { //增加一个多重签名账户信息到localdb中,第一次增加时账户在local中应该是不存在的。如果存在就返回错误 multiSig, err := getMultiSigAccount(m.GetLocalDB(), ownerOp.MultiSigAddr) @@ -566,7 +566,7 @@ func (m *MultiSig) saveMultiSigOwnerAddOrDel(ownerOp mty.ReceiptOwnerAddOrDel, a return kvs, nil } -//账户owner的mod/replace操作 +// 账户owner的mod/replace操作 func (m *MultiSig) saveMultiSigOwnerModOrRep(ownerOp mty.ReceiptOwnerModOrRep, addOrRollback bool) ([]*types.KeyValue, error) { //获取多重签名账户信息从db中 multiSig, err := getMultiSigAccount(m.GetLocalDB(), ownerOp.MultiSigAddr) @@ -608,7 +608,7 @@ func (m *MultiSig) saveMultiSigOwnerModOrRep(ownerOp mty.ReceiptOwnerModOrRep, a return kvs, nil } -//账户weight权重的mod操作 +// 账户weight权重的mod操作 func (m *MultiSig) saveMultiSigAccWeight(accountOp mty.ReceiptWeightModify, addOrRollback bool) ([]*types.KeyValue, error) { //获取多重签名账户信息从db中 multiSig, err := getMultiSigAccount(m.GetLocalDB(), accountOp.MultiSigAddr) @@ -633,7 +633,7 @@ func (m *MultiSig) saveMultiSigAccWeight(accountOp mty.ReceiptWeightModify, addO return kvs, nil } -//账户DailyLimit资产每日限额的add/mod操作 +// 账户DailyLimit资产每日限额的add/mod操作 func (m *MultiSig) saveMultiSigAccDailyLimit(accountOp mty.ReceiptDailyLimitOperate, addOrRollback bool) ([]*types.KeyValue, error) { //获取多重签名账户信息从db中 multiSig, err := getMultiSigAccount(m.GetLocalDB(), accountOp.MultiSigAddr) @@ -684,7 +684,7 @@ func (m *MultiSig) saveMultiSigAccDailyLimit(accountOp mty.ReceiptDailyLimitOper return kvs, nil } -//多重签名账户交易的Confirm/Revoke +// 多重签名账户交易的Confirm/Revoke func (m *MultiSig) saveMultiSigConfirmTx(confirmTx mty.ReceiptConfirmTx, addOrRollback bool) ([]*types.KeyValue, error) { multiSigAddr := confirmTx.MultiSigTxOwner.MultiSigAddr txid := confirmTx.MultiSigTxOwner.Txid @@ -733,8 +733,8 @@ func (m *MultiSig) saveMultiSigConfirmTx(confirmTx mty.ReceiptConfirmTx, addOrRo return kvs, nil } -//多重签名账户交易被确认执行,更新交易的执行结果以及增加确认owner -//包含转账的交易以及修改多重签名账户属性的交易 +// 多重签名账户交易被确认执行,更新交易的执行结果以及增加确认owner +// 包含转账的交易以及修改多重签名账户属性的交易 func (m *MultiSig) saveMultiSigTx(execTx mty.ReceiptMultiSigTx, addOrRollback bool) ([]*types.KeyValue, error) { multiSigAddr := execTx.MultiSigTxOwner.MultiSigAddr txid := execTx.MultiSigTxOwner.Txid @@ -809,7 +809,7 @@ func (m *MultiSig) saveMultiSigTx(execTx mty.ReceiptMultiSigTx, addOrRollback bo return kvs, nil } -//多重签名账户交易被确认执行,更新对应资产的每日限额信息,以及txcount计数 +// 多重签名账户交易被确认执行,更新对应资产的每日限额信息,以及txcount计数 func (m *MultiSig) saveDailyLimitUpdate(execTransfer mty.ReceiptAccDailyLimitUpdate, addOrRollback bool) ([]*types.KeyValue, error) { multiSigAddr := execTransfer.MultiSigAddr curDailyLimit := execTransfer.CurDailyLimit @@ -849,7 +849,7 @@ func (m *MultiSig) saveDailyLimitUpdate(execTransfer mty.ReceiptAccDailyLimitUpd return kvs, nil } -//多重签名账户交易被确认执行,更新对应资产的每日限额信息,以及txcount计数 +// 多重签名账户交易被确认执行,更新对应资产的每日限额信息,以及txcount计数 func (m *MultiSig) saveMultiSigTxCountUpdate(accTxCount mty.ReceiptTxCountUpdate, addOrRollback bool) ([]*types.KeyValue, error) { multiSigAddr := accTxCount.MultiSigAddr curTxCount := accTxCount.CurTxCount @@ -888,7 +888,7 @@ func (m *MultiSig) saveMultiSigTxCountUpdate(accTxCount mty.ReceiptTxCountUpdate return kvs, nil } -//获取多重签名账户的指定资产 +// 获取多重签名账户的指定资产 func (m *MultiSig) getMultiSigAccAssets(multiSigAddr string, assets *mty.Assets) (*types.Account, error) { symbol := getRealSymbol(assets.Symbol) cfg := m.GetAPI().GetConfig() @@ -905,7 +905,7 @@ func (m *MultiSig) getMultiSigAccAssets(multiSigAddr string, assets *mty.Assets) //内部共用接口 -//获取指定owner的weight权重,owner所在的index,所有owners的weight权重之和,以及owner是否存在 +// 获取指定owner的weight权重,owner所在的index,所有owners的weight权重之和,以及owner是否存在 func getOwnerInfoByAddr(multiSigAcc *mty.MultiSig, oldowner string) (uint64, int, uint64, int, bool) { //首先遍历所有owners,确定对应的owner已近存在. var findindex int @@ -930,7 +930,7 @@ func getOwnerInfoByAddr(multiSigAcc *mty.MultiSig, oldowner string) (uint64, int return oldweight, findindex, totalweight, totalowner, true } -//确认某笔交易是否已经达到确认需要的权重 +// 确认某笔交易是否已经达到确认需要的权重 func isConfirmed(requiredWeight uint64, multiSigTx *mty.MultiSigTx) bool { var totalweight uint64 for _, owner := range multiSigTx.ConfirmedOwner { @@ -939,7 +939,7 @@ func isConfirmed(requiredWeight uint64, multiSigTx *mty.MultiSigTx) bool { return totalweight >= requiredWeight } -//确认某笔交易的额度是否满足每日限额,返回是否满足,以及新的newLastDay时间 +// 确认某笔交易的额度是否满足每日限额,返回是否满足,以及新的newLastDay时间 func isUnderLimit(blocktime int64, amount uint64, dailyLimit *mty.DailyLimit) (bool, int64) { var lastDay int64 @@ -960,7 +960,7 @@ func isUnderLimit(blocktime int64, amount uint64, dailyLimit *mty.DailyLimit) (b return true, lastDay } -//确定这个地址是否是此multiSigAcc多重签名账户的owner,如果是owner的话并返回weight权重 +// 确定这个地址是否是此multiSigAcc多重签名账户的owner,如果是owner的话并返回weight权重 func isOwner(multiSigAcc *mty.MultiSig, ownerAddr string) (uint64, bool) { for _, owner := range multiSigAcc.Owners { if owner.OwnerAddr == ownerAddr { @@ -970,7 +970,7 @@ func isOwner(multiSigAcc *mty.MultiSig, ownerAddr string) (uint64, bool) { return 0, false } -//删除指定index的owner从owners列表中 +// 删除指定index的owner从owners列表中 func delOwner(Owners []*mty.Owner, index int) []*mty.Owner { ownerSize := len(Owners) multisiglog.Error("delOwner", "ownerSize", ownerSize, "index", index) @@ -987,7 +987,7 @@ func delOwner(Owners []*mty.Owner, index int) []*mty.Owner { return Owners } -//指定资产是否设置了每日限额 +// 指定资产是否设置了每日限额 func isDailyLimit(multiSigAcc *mty.MultiSig, execer, symbol string) (int, bool) { for index, dailyLimit := range multiSigAcc.DailyLimits { if dailyLimit.Execer == execer && dailyLimit.Symbol == symbol { @@ -997,7 +997,7 @@ func isDailyLimit(multiSigAcc *mty.MultiSig, execer, symbol string) (int, bool) return 0, false } -//owner是否已经确认过某个txid,已经确认过就返回index +// owner是否已经确认过某个txid,已经确认过就返回index func isOwnerConfirmedTx(multiSigTx *mty.MultiSigTx, ownerAddr string) (int, bool) { for index, owner := range multiSigTx.ConfirmedOwner { if owner.OwnerAddr == ownerAddr { @@ -1007,7 +1007,7 @@ func isOwnerConfirmedTx(multiSigTx *mty.MultiSigTx, ownerAddr string) (int, bool return 0, false } -//通过txhash获取tx交易信息 +// 通过txhash获取tx交易信息 func getTxByHash(api client.QueueProtocolAPI, txHash string) (*types.TransactionDetail, error) { hash, err := hex.DecodeString(txHash) if err != nil { @@ -1030,7 +1030,7 @@ func getTxByHash(api client.QueueProtocolAPI, txHash string) (*types.Transaction return txs.Txs[0], nil } -//从tx交易中解析payload信息 +// 从tx交易中解析payload信息 func getMultiSigTxPayload(tx *types.TransactionDetail) (*mty.MultiSigAction, error) { if !bytes.HasSuffix(tx.Tx.Execer, []byte(mty.MultiSigX)) { multisiglog.Error("GetMultiSigTx", "tx.Tx.Execer", string(tx.Tx.Execer), "MultiSigX", mty.MultiSigX) @@ -1046,7 +1046,7 @@ func getMultiSigTxPayload(tx *types.TransactionDetail) (*mty.MultiSigAction, err return &payload, nil } -//bty 显示是大写,在底层mavl数据库中对应key值时使用小写 +// bty 显示是大写,在底层mavl数据库中对应key值时使用小写 func getRealSymbol(symbol string) string { if symbol == types.BTY { return "bty" diff --git a/plugin/dapp/multisig/executor/multisigdb.go b/plugin/dapp/multisig/executor/multisigdb.go index 80acf1bda2..bafd0f28e5 100644 --- a/plugin/dapp/multisig/executor/multisigdb.go +++ b/plugin/dapp/multisig/executor/multisigdb.go @@ -46,7 +46,7 @@ func setMultiSigAccToDb(db dbm.KV, multiSigAcc *mty.MultiSig) ([]byte, []byte) { return key, value } -//获取db中指定多重签名地址上的txid对应的交易信息 +// 获取db中指定多重签名地址上的txid对应的交易信息 func getMultiSigAccTxFromDb(db dbm.KV, multiSigAddr string, txid uint64) (*mty.MultiSigTx, error) { //首先从statedb中获取MultiSigAccTx的状态信息 @@ -86,7 +86,7 @@ func getMultiSigAccCountKV(count int64) *types.KeyValue { return kv } -//获取创建的多重账户的数量 +// 获取创建的多重账户的数量 func getMultiSigAccCount(db dbm.KVDB) (int64, error) { count := types.Int64{} value, err := db.Get(calcMultiSigAccCountKey()) @@ -106,14 +106,14 @@ func getMultiSigAccCount(db dbm.KVDB) (int64, error) { return count.Data, nil } -//设置创建的多重账户的数量 +// 设置创建的多重账户的数量 func setMultiSigAccCount(db dbm.KVDB, count int64) error { value := &types.Int64{Data: count} valuebytes := types.Encode(value) return db.Set(calcMultiSigAccCountKey(), valuebytes) } -//更新多重签名账户计数 +// 更新多重签名账户计数 func updateMultiSigAccCount(cachedb dbm.KVDB, isadd bool) (*types.KeyValue, error) { count, err := getMultiSigAccCount(cachedb) if err != nil { @@ -135,7 +135,7 @@ func updateMultiSigAccCount(cachedb dbm.KVDB, isadd bool) (*types.KeyValue, erro return getMultiSigAccCountKV(count), nil } -//获取多重账户信息通过key值 +// 获取多重账户信息通过key值 func getMultiSigAccount(db dbm.KVDB, addr string) (*mty.MultiSig, error) { multiSigAcc := &mty.MultiSig{} value, err := db.Get(calcMultiSigAcc(addr)) @@ -155,7 +155,7 @@ func getMultiSigAccount(db dbm.KVDB, addr string) (*mty.MultiSig, error) { return multiSigAcc, nil } -//设置多重签名账户信息到db中通过key值, +// 设置多重签名账户信息到db中通过key值, func setMultiSigAccount(db dbm.KVDB, multiSig *mty.MultiSig, isadd bool) error { valuebytes := types.Encode(multiSig) if isadd { @@ -164,7 +164,7 @@ func setMultiSigAccount(db dbm.KVDB, multiSig *mty.MultiSig, isadd bool) error { return db.Set(calcMultiSigAcc(multiSig.MultiSigAddr), nil) } -//获取多重签名账户的kv对 +// 获取多重签名账户的kv对 func getMultiSigAccountKV(multiSig *mty.MultiSig, isadd bool) *types.KeyValue { accountbytes := types.Encode(multiSig) var kv *types.KeyValue @@ -176,7 +176,7 @@ func getMultiSigAccountKV(multiSig *mty.MultiSig, isadd bool) *types.KeyValue { return kv } -//更新多重签名账户列表 +// 更新多重签名账户列表 func updateMultiSigAccList(db dbm.KVDB, addr string, index int64, isadd bool) (*types.KeyValue, error) { oldaddr, err := getMultiSigAccList(db, index) if err != nil { @@ -219,8 +219,8 @@ func getMultiSigAccList(db dbm.KVDB, index int64) (string, error) { return string(value), nil } -//MultiSigTx: -//获取多重签名账户的交易信息 +// MultiSigTx: +// 获取多重签名账户的交易信息 func getMultiSigTx(db dbm.KVDB, addr string, txid uint64) (*mty.MultiSigTx, error) { multiSigTx := &mty.MultiSigTx{} value, err := db.Get(calcMultiSigAccTx(addr, txid)) @@ -240,7 +240,7 @@ func getMultiSigTx(db dbm.KVDB, addr string, txid uint64) (*mty.MultiSigTx, erro return multiSigTx, nil } -//设置多重签名账户交易信息到db中通过key值, 交易添加和回滚删除 +// 设置多重签名账户交易信息到db中通过key值, 交易添加和回滚删除 func setMultiSigTx(db dbm.KVDB, multiSigTx *mty.MultiSigTx, isadd bool) error { valuebytes := types.Encode(multiSigTx) if isadd { @@ -249,7 +249,7 @@ func setMultiSigTx(db dbm.KVDB, multiSigTx *mty.MultiSigTx, isadd bool) error { return db.Set(calcMultiSigAccTx(multiSigTx.MultiSigAddr, multiSigTx.Txid), nil) } -//获取多重签名账户交易的kv对 +// 获取多重签名账户交易的kv对 func getMultiSigTxKV(multiSigTx *mty.MultiSigTx, isadd bool) *types.KeyValue { accountbytes := types.Encode(multiSigTx) var kv *types.KeyValue @@ -316,8 +316,8 @@ func setAddrReciver(db dbm.KVDB, addr, execname, symbol string, reciverAmount in return db.Set(kv.Key, kv.Value) } -//MultiSigAccAddress: -//获取指定地址创建的所有MultiSigAddress +// MultiSigAccAddress: +// 获取指定地址创建的所有MultiSigAddress func getMultiSigAddress(db dbm.KVDB, createAddr string) (*mty.AccAddress, error) { address := &mty.AccAddress{} value, err := db.Get(calcMultiSigAccCreateAddr(createAddr)) @@ -337,7 +337,7 @@ func getMultiSigAddress(db dbm.KVDB, createAddr string) (*mty.AccAddress, error) return address, nil } -//需要处理交易添加和回滚删除 +// 需要处理交易添加和回滚删除 func setMultiSigAddress(db dbm.KVDB, createAddr, multiSigAddr string, isadd bool) *types.KeyValue { accAddress, err := getMultiSigAddress(db, createAddr) if err != nil { @@ -369,7 +369,7 @@ func setMultiSigAddress(db dbm.KVDB, createAddr, multiSigAddr string, isadd bool return &types.KeyValue{Key: key, Value: value} } -//获取指定地址创建的所有MultiSigAddress +// 获取指定地址创建的所有MultiSigAddress func getMultiSigAccAllAddress(db dbm.KVDB, createAddr string) (*mty.AccAddress, error) { address := &mty.AccAddress{} value, err := db.Get(calcMultiSigAccCreateAddr(createAddr)) @@ -389,7 +389,7 @@ func getMultiSigAccAllAddress(db dbm.KVDB, createAddr string) (*mty.AccAddress, return address, nil } -//获取指定账户地址上接受的所有资产 +// 获取指定账户地址上接受的所有资产 func getMultiSigAccAllAssets(db dbm.KVDB, addr string) ([][]byte, error) { values, err := db.List(calcAddrRecvAmountPrefix(addr), nil, 0, 0) if err != nil && err != types.ErrNotFound { diff --git a/plugin/dapp/multisig/executor/query.go b/plugin/dapp/multisig/executor/query.go index db226410aa..e6fb36e9e1 100644 --- a/plugin/dapp/multisig/executor/query.go +++ b/plugin/dapp/multisig/executor/query.go @@ -11,8 +11,8 @@ import ( mty "github.com/33cn/plugin/plugin/dapp/multisig/types" ) -//Query_MultiSigAccCount 获取多重签名账户的数量,用于分批获取多重签名账户地址 -//返回ReplyMultiSigAccounts +// Query_MultiSigAccCount 获取多重签名账户的数量,用于分批获取多重签名账户地址 +// 返回ReplyMultiSigAccounts func (m *MultiSig) Query_MultiSigAccCount(in *types.ReqNil) (types.Message, error) { db := m.GetLocalDB() count, err := getMultiSigAccCount(db) @@ -23,14 +23,17 @@ func (m *MultiSig) Query_MultiSigAccCount(in *types.ReqNil) (types.Message, erro return &types.Int64{Data: count}, nil } -//Query_MultiSigAccounts 获取指定区间的多重签名账户 -//输入: -//message ReqMultiSigAccs { -// int64 start = 1; -// int64 end = 2; -//输出: -//message ReplyMultiSigAccs { -// repeated string address = 1; +// Query_MultiSigAccounts 获取指定区间的多重签名账户 +// 输入: +// +// message ReqMultiSigAccs { +// int64 start = 1; +// int64 end = 2; +// +// 输出: +// +// message ReplyMultiSigAccs { +// repeated string address = 1; func (m *MultiSig) Query_MultiSigAccounts(in *mty.ReqMultiSigAccs) (types.Message, error) { accountAddrs := &mty.ReplyMultiSigAccs{} @@ -67,18 +70,21 @@ func (m *MultiSig) validateMultiSignAddr(addr string) error { return multiSignDriver.ValidateAddr(addr) } -//Query_MultiSigAccountInfo 获取指定多重签名账号的状态信息 -//输入: -//message ReqMultiSigAccountInfo { -// string MultiSigAccAddr = 1; -//返回: -//message MultiSig { -// string createAddr = 1; -// string multiSigAddr = 2; -// repeated Owner owners = 3; -// repeated DailyLimit dailyLimits = 4; -// uint64 txCount = 5; -// uint64 requiredWeight = 6; +// Query_MultiSigAccountInfo 获取指定多重签名账号的状态信息 +// 输入: +// +// message ReqMultiSigAccountInfo { +// string MultiSigAccAddr = 1; +// +// 返回: +// +// message MultiSig { +// string createAddr = 1; +// string multiSigAddr = 2; +// repeated Owner owners = 3; +// repeated DailyLimit dailyLimits = 4; +// uint64 txCount = 5; +// uint64 requiredWeight = 6; func (m *MultiSig) Query_MultiSigAccountInfo(in *mty.ReqMultiSigAccInfo) (types.Message, error) { if in == nil { return nil, types.ErrInvalidParam @@ -99,12 +105,14 @@ func (m *MultiSig) Query_MultiSigAccountInfo(in *mty.ReqMultiSigAccInfo) (types. return multiSigAcc, nil } -//Query_MultiSigAccTxCount 获取指定多重签名账号下的tx交易数量 -//输入: -//message ReqMultiSigAccountInfo { -// string MultiSigAccAddr = 1; -//返回: -//uint64 +// Query_MultiSigAccTxCount 获取指定多重签名账号下的tx交易数量 +// 输入: +// +// message ReqMultiSigAccountInfo { +// string MultiSigAccAddr = 1; +// +// 返回: +// uint64 func (m *MultiSig) Query_MultiSigAccTxCount(in *mty.ReqMultiSigAccInfo) (types.Message, error) { if in == nil { return nil, types.ErrInvalidParam @@ -126,18 +134,21 @@ func (m *MultiSig) Query_MultiSigAccTxCount(in *mty.ReqMultiSigAccInfo) (types.M return &mty.Uint64{Data: multiSigAcc.TxCount}, nil } -//Query_MultiSigTxids 获取txids通过设置的过滤条件和区间,pending, executed -//输入: -//message ReqMultiSigTxids { -// string multisigaddr = 1; -// uint64 fromtxid = 2; -// uint64 totxid = 3; -// bool pending = 4; -// bool executed = 5; +// Query_MultiSigTxids 获取txids通过设置的过滤条件和区间,pending, executed +// 输入: +// +// message ReqMultiSigTxids { +// string multisigaddr = 1; +// uint64 fromtxid = 2; +// uint64 totxid = 3; +// bool pending = 4; +// bool executed = 5; +// // 返回: -//message ReplyMultiSigTxids { -// string multisigaddr = 1; -// repeated uint64 txids = 2; +// +// message ReplyMultiSigTxids { +// string multisigaddr = 1; +// repeated uint64 txids = 2; func (m *MultiSig) Query_MultiSigTxids(in *mty.ReqMultiSigTxids) (types.Message, error) { if in == nil || in.FromTxId > in.ToTxId || in.FromTxId < 0 { return nil, types.ErrInvalidParam @@ -175,15 +186,18 @@ func (m *MultiSig) Query_MultiSigTxids(in *mty.ReqMultiSigTxids) (types.Message, } -//Query_MultiSigTxInfo 获取txid交易的信息,以及参与确认的owner信息 -//输入: -//message ReqMultiSigTxInfo { -// string multisigaddr = 1; -// uint64 txid = 2; -//返回: -//message ReplyMultiSigTxInfo { -// MultiSigTransaction multisigtxinfo = 1; -// repeated Owner confirmowners = 3; +// Query_MultiSigTxInfo 获取txid交易的信息,以及参与确认的owner信息 +// 输入: +// +// message ReqMultiSigTxInfo { +// string multisigaddr = 1; +// uint64 txid = 2; +// +// 返回: +// +// message ReplyMultiSigTxInfo { +// MultiSigTransaction multisigtxinfo = 1; +// repeated Owner confirmowners = 3; func (m *MultiSig) Query_MultiSigTxInfo(in *mty.ReqMultiSigTxInfo) (types.Message, error) { if in == nil { return nil, types.ErrInvalidParam @@ -208,13 +222,15 @@ func (m *MultiSig) Query_MultiSigTxInfo(in *mty.ReqMultiSigTxInfo) (types.Messag return multiSigTx, nil } -//Query_MultiSigTxConfirmedWeight 获取txid交易已经确认的权重之和 -//输入: -//message ReqMultiSigTxInfo { -// string multisigaddr = 1; -// uint64 txid = 2; -//返回: -//message Int64 +// Query_MultiSigTxConfirmedWeight 获取txid交易已经确认的权重之和 +// 输入: +// +// message ReqMultiSigTxInfo { +// string multisigaddr = 1; +// uint64 txid = 2; +// +// 返回: +// message Int64 func (m *MultiSig) Query_MultiSigTxConfirmedWeight(in *mty.ReqMultiSigTxInfo) (types.Message, error) { if in == nil { return nil, types.ErrInvalidParam @@ -242,15 +258,18 @@ func (m *MultiSig) Query_MultiSigTxConfirmedWeight(in *mty.ReqMultiSigTxInfo) (t return &mty.Uint64{Data: totalWeight}, nil } -//Query_MultiSigAccUnSpentToday 获取指定资产当日还能使用的免多重签名的余额 -//输入: -//message ReqMultiSigAccUnSpentToday { -// string multiSigAddr = 1; -// string execer = 2; -// string symbol = 3; -//返回: -//message ReplyMultiSigAccUnSpentToday { -// uint64 amount = 1; +// Query_MultiSigAccUnSpentToday 获取指定资产当日还能使用的免多重签名的余额 +// 输入: +// +// message ReqMultiSigAccUnSpentToday { +// string multiSigAddr = 1; +// string execer = 2; +// string symbol = 3; +// +// 返回: +// +// message ReplyMultiSigAccUnSpentToday { +// uint64 amount = 1; func (m *MultiSig) Query_MultiSigAccUnSpentToday(in *mty.ReqAccAssets) (types.Message, error) { if in == nil { return nil, types.ErrInvalidParam @@ -313,17 +332,20 @@ func (m *MultiSig) Query_MultiSigAccUnSpentToday(in *mty.ReqAccAssets) (types.Me return replyUnSpentAssets, nil } -//Query_MultiSigAccAssets 获取多重签名账户上的所有资产,或者指定资产 -//输入: -//message ReqAccAssets { -// string multiSigAddr = 1; -// Assets assets = 2; -// bool isAll = 3; -//返回: -//message MultiSigAccAssets { -// Assets assets = 1; -// int64 recvAmount = 2; -// Account account = 3; +// Query_MultiSigAccAssets 获取多重签名账户上的所有资产,或者指定资产 +// 输入: +// +// message ReqAccAssets { +// string multiSigAddr = 1; +// Assets assets = 2; +// bool isAll = 3; +// +// 返回: +// +// message MultiSigAccAssets { +// Assets assets = 1; +// int64 recvAmount = 2; +// Account account = 3; func (m *MultiSig) Query_MultiSigAccAssets(in *mty.ReqAccAssets) (types.Message, error) { if in == nil { return nil, types.ErrInvalidParam @@ -387,11 +409,11 @@ func (m *MultiSig) Query_MultiSigAccAssets(in *mty.ReqAccAssets) (types.Message, return replyAccAssets, nil } -//Query_MultiSigAccAllAddress 获取指定地址创建的所有多重签名账户 -//输入: -//createaddr -//返回: -//[]string +// Query_MultiSigAccAllAddress 获取指定地址创建的所有多重签名账户 +// 输入: +// createaddr +// 返回: +// []string func (m *MultiSig) Query_MultiSigAccAllAddress(in *mty.ReqMultiSigAccInfo) (types.Message, error) { if in == nil { return nil, types.ErrInvalidParam diff --git a/plugin/dapp/multisig/rpc/jrpc_channel_test.go b/plugin/dapp/multisig/rpc/jrpc_channel_test.go index c60f440eac..ccc3442c8c 100644 --- a/plugin/dapp/multisig/rpc/jrpc_channel_test.go +++ b/plugin/dapp/multisig/rpc/jrpc_channel_test.go @@ -72,7 +72,7 @@ func TestJRPCChannel(t *testing.T) { } } -//创建交易 +// 创建交易 func testCreateMultiSigAccCreateCmd(t *testing.T, jrpc *jsonclient.JSONClient) error { params := &mty.MultiSigAccCreate{} return jrpc.Call("multisig.MultiSigAccCreateTx", params, nil) @@ -116,7 +116,7 @@ func testCreateMultiSigAccTransferOutCmd(t *testing.T, jrpc *jsonclient.JSONClie return jrpc.Call("multisig.MultiSigAccTransferOutTx", params, nil) } -//get 多重签名账户信息 +// get 多重签名账户信息 func testGetMultiSigAccCountCmd(t *testing.T, jrpc *jsonclient.JSONClient) error { params := &rpctypes.Query4Jrpc{ Execer: mty.MultiSigX, diff --git a/plugin/dapp/multisig/rpc/rpc_real_test.go b/plugin/dapp/multisig/rpc/rpc_real_test.go index 9747d74a49..c6602bc8f4 100644 --- a/plugin/dapp/multisig/rpc/rpc_real_test.go +++ b/plugin/dapp/multisig/rpc/rpc_real_test.go @@ -104,7 +104,7 @@ func TestMultiSigAccount(t *testing.T) { testAbnormal(t, mocker, jrpcClient) } -//创建多重签名账户 +// 创建多重签名账户 func testAccCreateTx(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient) string { gen := mocker.GetGenesisKey() var params rpctypes.Query4Jrpc @@ -204,7 +204,7 @@ func testAccCreateTx(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jso return multiSigAccAddr } -//多重签名地址转入操作 +// 多重签名地址转入操作 func testTransferInTx(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() var params rpctypes.Query4Jrpc @@ -280,7 +280,7 @@ func testTransferInTx(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *js //t.Log(rep4) } -//多重签名地址转出操作 AddrB +// 多重签名地址转出操作 AddrB func testTransferOutTx(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() var params rpctypes.Query4Jrpc @@ -347,7 +347,7 @@ func testTransferOutTx(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *j //t.Log(rep8) } -//owner add AddrE +// owner add AddrE func testAddOwner(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() var params rpctypes.Query4Jrpc @@ -390,7 +390,7 @@ func testAddOwner(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsoncl //t.Log(rep10) } -//owner del AddrE +// owner del AddrE func testDelOwner(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() var params rpctypes.Query4Jrpc @@ -433,7 +433,7 @@ func testDelOwner(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsoncl //t.Log(rep) } -//ModifyOwnerWeight +// ModifyOwnerWeight func testModifyOwnerWeight(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() var params rpctypes.Query4Jrpc @@ -477,7 +477,7 @@ func testModifyOwnerWeight(t *testing.T, mocker *testnode.Chain33Mock, jrpcClien //t.Log(rep) } -//testReplaceOwner owner AddrA replace by AddrE +// testReplaceOwner owner AddrA replace by AddrE func testReplaceOwner(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() var params rpctypes.Query4Jrpc @@ -521,7 +521,7 @@ func testReplaceOwner(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *js //t.Log(rep) } -//testModifyDailyLimit modify dailylimit coins:BTY 1200000000 +// testModifyDailyLimit modify dailylimit coins:BTY 1200000000 func testModifyDailyLimit(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() var params rpctypes.Query4Jrpc @@ -569,7 +569,7 @@ func testModifyDailyLimit(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient //t.Log(rep) } -//testAddDailyLimit add dailylimit token:HYB 1000000000 +// testAddDailyLimit add dailylimit token:HYB 1000000000 func testAddDailyLimit(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() var params rpctypes.Query4Jrpc @@ -617,7 +617,7 @@ func testAddDailyLimit(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *j //t.Log(rep) } -//testModifyRequestWeight Modify RequestWeight 16 +// testModifyRequestWeight Modify RequestWeight 16 func testModifyRequestWeight(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() var params rpctypes.Query4Jrpc @@ -796,7 +796,7 @@ func testConfirmTx(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonc } -//查询txid的交易Confirm信息 +// 查询txid的交易Confirm信息 func checkTxInfo(t *testing.T, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string, txid uint64, executed bool, ownerAddr string) { var params rpctypes.Query4Jrpc @@ -873,7 +873,7 @@ func checkMultiSigAccAssets(t *testing.T, jrpcClient *jsonclient.JSONClient, add //t.Log(rep) } -//异常测试,主要是参数的合法性校验 +// 异常测试,主要是参数的合法性校验 func testAbnormal(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient) { //1. MultiSigAccCreateTx owner重复 var owners []*mty.Owner diff --git a/plugin/dapp/multisig/types/const.go b/plugin/dapp/multisig/types/const.go index 4ed918382a..e3d8b12f0d 100644 --- a/plugin/dapp/multisig/types/const.go +++ b/plugin/dapp/multisig/types/const.go @@ -47,7 +47,7 @@ const ( ActionMultiSigExecTransferFrom = 10005 ) -//多重签名账户执行输出的logid +// 多重签名账户执行输出的logid const ( TyLogMultiSigAccCreate = 10000 //只输出多重签名的账户地址 @@ -69,7 +69,7 @@ const ( ) -//AccAssetsResult 账户资产cli的显示,主要是amount需要转换成浮点型字符串 +// AccAssetsResult 账户资产cli的显示,主要是amount需要转换成浮点型字符串 type AccAssetsResult struct { Execer string `json:"execer,omitempty"` Symbol string `json:"symbol,omitempty"` @@ -80,7 +80,7 @@ type AccAssetsResult struct { Addr string `json:"addr,omitempty"` } -//DailyLimitResult 每日限额信息的显示cli +// DailyLimitResult 每日限额信息的显示cli type DailyLimitResult struct { Symbol string `json:"symbol,omitempty"` Execer string `json:"execer,omitempty"` @@ -89,7 +89,7 @@ type DailyLimitResult struct { LastDay string `json:"lastday,omitempty"` } -//MultiSigResult 多重签名账户信息的显示cli +// MultiSigResult 多重签名账户信息的显示cli type MultiSigResult struct { CreateAddr string `json:"createAddr,omitempty"` MultiSigAddr string `json:"multiSigAddr,omitempty"` @@ -99,14 +99,14 @@ type MultiSigResult struct { RequiredWeight uint64 `json:"requiredWeight,omitempty"` } -//UnSpentAssetsResult 每日限额之内未花费额度的显示cli +// UnSpentAssetsResult 每日限额之内未花费额度的显示cli type UnSpentAssetsResult struct { Symbol string `json:"symbol,omitempty"` Execer string `json:"execer,omitempty"` UnSpent string `json:"unspent,omitempty"` } -//IsAssetsInvalid 资产的合法性检测,Symbol:必须全部大写,例如:BTY,coins.BTY。exec:必须在types.AllowUserExec中存在 +// IsAssetsInvalid 资产的合法性检测,Symbol:必须全部大写,例如:BTY,coins.BTY。exec:必须在types.AllowUserExec中存在 func IsAssetsInvalid(exec, symbol string) error { //exec检测 diff --git a/plugin/dapp/multisig/types/errors.go b/plugin/dapp/multisig/types/errors.go index c1a20272ee..3b00aa2fac 100644 --- a/plugin/dapp/multisig/types/errors.go +++ b/plugin/dapp/multisig/types/errors.go @@ -6,7 +6,7 @@ package types import "errors" -//multisig 合约的错误码 +// multisig 合约的错误码 var ( ErrRequiredweight = errors.New("ErrRequiredweight") ErrCreatAccountAddr = errors.New("ErrCreatAccountAddr") diff --git a/plugin/dapp/multisig/types/multisig.pb.go b/plugin/dapp/multisig/types/multisig.pb.go index a6864aa1d0..12c6ba0456 100644 --- a/plugin/dapp/multisig/types/multisig.pb.go +++ b/plugin/dapp/multisig/types/multisig.pb.go @@ -22,10 +22,10 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -////////////////////////////////////////////////////////////////////////////// +// //////////////////////////////////////////////////////////////////////////// // message for multisig start///////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -//多重签名账户的状态信息,存在在statedb中,通过多重签名账户作为key值 +// //////////////////////////////////////////////////////////////////////////// +// 多重签名账户的状态信息,存在在statedb中,通过多重签名账户作为key值 // createaddr: 创建多重签名地址的创建者账户 // multisigaddr: 多重签名地址 // owners: 可以操作此多重签名地址的owner账户列表 @@ -119,7 +119,7 @@ func (x *MultiSig) GetRequiredWeight() uint64 { return 0 } -//这个地址是否已经确认某个交易 +// 这个地址是否已经确认某个交易 type ConfirmedOwner struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -167,7 +167,7 @@ func (x *ConfirmedOwner) GetConfirmedOwner() []*Owner { return nil } -//记录提交的交易详情,在满足确认条件后执行data中的交易 +// 记录提交的交易详情,在满足确认条件后执行data中的交易 // txHash:用于存贮提交的确认交易。存贮在localdb中,通过txhash可以获取 type MultiSigTx struct { state protoimpl.MessageState @@ -312,7 +312,7 @@ func (x *Owner) GetWeight() uint64 { return 0 } -//每日资产限额,不同的资产价格不一致,需要设置各自的每日限额。没有设置或者限额是0时,表示不能取币 +// 每日资产限额,不同的资产价格不一致,需要设置各自的每日限额。没有设置或者限额是0时,表示不能取币 // spentToday今天已经花费的额度。用于和dailyLimit做对比,超过每日限额时需要多重签名 // lastDay记录当天开始的时间戳,新的一天需要重置spentToday为初始值0,并修改lastDay的时间戳 type DailyLimit struct { @@ -602,7 +602,7 @@ func (*MultiSigAction_MultiSigExecTransferTo) isMultiSigAction_Value() {} func (*MultiSigAction_MultiSigExecTransferFrom) isMultiSigAction_Value() {} -//创建多重签名账户时需要的信息:创建时最少初始化两个owners,资产的每日限额初始时可以不设置 +// 创建多重签名账户时需要的信息:创建时最少初始化两个owners,资产的每日限额初始时可以不设置 type MultiSigAccCreate struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -666,7 +666,7 @@ func (x *MultiSigAccCreate) GetDailyLimit() *SymbolDailyLimit { return nil } -//对MultiSigAccount账户owner的操作:add/del/replace/modify +// 对MultiSigAccount账户owner的操作:add/del/replace/modify type MultiSigOwnerOperate struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -746,8 +746,8 @@ func (x *MultiSigOwnerOperate) GetOperateFlag() uint64 { return 0 } -//对MultiSigAccount账户的操作:modify/add:SymbolDailyLimit,requiredweight -//修改或者添加每日限额,或者请求权重的值。 +// 对MultiSigAccount账户的操作:modify/add:SymbolDailyLimit,requiredweight +// 修改或者添加每日限额,或者请求权重的值。 type MultiSigAccOperate struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -819,9 +819,9 @@ func (x *MultiSigAccOperate) GetOperateFlag() bool { return false } -//多重签名合约中账户之间转币操作:增加一个from的字段实现MultiSigAddr--->addr之间的转账 -//需要判断from地址是否是多重签名地址 -//将MultiSig合约中from地址上execname+symbol的资产转移到to地址 +// 多重签名合约中账户之间转币操作:增加一个from的字段实现MultiSigAddr--->addr之间的转账 +// 需要判断from地址是否是多重签名地址 +// 将MultiSig合约中from地址上execname+symbol的资产转移到to地址 type MultiSigExecTransferFrom struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -909,9 +909,9 @@ func (x *MultiSigExecTransferFrom) GetFrom() string { return "" } -//多重签名合约中账户之间转币操作: addr --->MultiSigAddr之间的转账 -//需要判断to地址是否是多重签名地址 -//将MultiSig合约中签名地址上execname+symbol的资产转移到to地址 +// 多重签名合约中账户之间转币操作: addr --->MultiSigAddr之间的转账 +// 需要判断to地址是否是多重签名地址 +// 将MultiSig合约中签名地址上execname+symbol的资产转移到to地址 type MultiSigExecTransferTo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -991,7 +991,7 @@ func (x *MultiSigExecTransferTo) GetTo() string { return "" } -//多重签名账户withdraw交易的确认或者取消确认 +// 多重签名账户withdraw交易的确认或者取消确认 // multisigaccaddr:多重签名账户地址 // transactionid:多重签名账户上的withdraw交易的内部id type MultiSigConfirmTx struct { @@ -1057,7 +1057,7 @@ func (x *MultiSigConfirmTx) GetConfirmOrRevoke() bool { return false } -//获取所有多重签名账号 +// 获取所有多重签名账号 type ReqMultiSigAccs struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1160,7 +1160,7 @@ func (x *ReplyMultiSigAccs) GetAddress() []string { return nil } -//获取指定多重签名账号的状态信息 +// 获取指定多重签名账号的状态信息 type ReqMultiSigAccInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1208,7 +1208,7 @@ func (x *ReqMultiSigAccInfo) GetMultiSigAccAddr() string { return "" } -//指定多重签名账号的状态信息 +// 指定多重签名账号的状态信息 type ReplyMultiSigAccInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1296,7 +1296,7 @@ func (x *ReplyMultiSigAccInfo) GetRequiredWeight() uint64 { return 0 } -//获取txids设置过滤条件和区间,pending, executed +// 获取txids设置过滤条件和区间,pending, executed type ReqMultiSigTxids struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1431,7 +1431,7 @@ func (x *ReplyMultiSigTxids) GetTxids() []uint64 { return nil } -//获取txid交易的信息,以及参与确认的owner信息 +// 获取txid交易的信息,以及参与确认的owner信息 type ReqMultiSigTxInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1534,7 +1534,7 @@ func (x *ReplyMultiSigTxInfo) GetMultiSigTxInfo() *MultiSigTx { return nil } -//获取指定资产当日剩余的免多重签名的余额 +// 获取指定资产当日剩余的免多重签名的余额 type ReqMultiSigAccUnSpentToday struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1884,7 +1884,7 @@ func (x *ReceiptOwnerModOrRep) GetModOrRep() bool { return false } -//多重签名账户的操作:ReqWeight,AssetDailyLimit +// 多重签名账户的操作:ReqWeight,AssetDailyLimit // TyLogMultiSigAccWeightModify = 10005 //输出修改前后确认权重的值:preReqWeight和curReqWeight type ReceiptWeightModify struct { state protoimpl.MessageState @@ -2022,7 +2022,7 @@ func (x *ReceiptDailyLimitOperate) GetAddOrModify() bool { return false } -//交易确认或者撤销(撤销值针对未执行的交易) +// 交易确认或者撤销(撤销值针对未执行的交易) // TyLogMultiSigConfirmTx = 10008 //输出确认的交易id,以及owner信息:addr+weight // TyLogMultiSigConfirmTxRevoke = 10009 //输出撤销确认的交易id,以及owner信息:addr+weight type ReceiptConfirmTx struct { @@ -2080,7 +2080,7 @@ func (x *ReceiptConfirmTx) GetConfirmeOrRevoke() bool { return false } -//可能会修改dailyLimit的相关属性 +// 可能会修改dailyLimit的相关属性 type ReceiptAccDailyLimitUpdate struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2144,7 +2144,7 @@ func (x *ReceiptAccDailyLimitUpdate) GetCurDailyLimit() *DailyLimit { return nil } -//执行MultiSigAcc相关的交易可能会修改tx的执行状态和增加确认owner +// 执行MultiSigAcc相关的交易可能会修改tx的执行状态和增加确认owner type ReceiptMultiSigTx struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2397,7 +2397,7 @@ func (x *Uint64) GetData() uint64 { return 0 } -//记录账户收到固定资产的数量 +// 记录账户收到固定资产的数量 type AccountAssets struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2461,7 +2461,7 @@ func (x *AccountAssets) GetAmount() int64 { return 0 } -//获取多重签名账户上的指定资产或者所有资产 +// 获取多重签名账户上的指定资产或者所有资产 type ReqAccAssets struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2572,7 +2572,7 @@ func (x *ReplyAccAssets) GetAccAssets() []*AccAssets { return nil } -//账户资产信息 +// 账户资产信息 type AccAssets struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2691,7 +2691,7 @@ func (x *Assets) GetSymbol() string { return "" } -//账户地址列表 +// 账户地址列表 type AccAddress struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/multisig/types/types.go b/plugin/dapp/multisig/types/types.go index a33ce980e9..82452fe6ac 100644 --- a/plugin/dapp/multisig/types/types.go +++ b/plugin/dapp/multisig/types/types.go @@ -16,12 +16,12 @@ func init() { types.RegExec(MultiSigX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(MultiSigX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(MultiSigX, NewType(cfg)) } @@ -39,17 +39,17 @@ func NewType(cfg *types.Chain33Config) *MultiSigType { return c } -//GetPayload 获取交易payload的结构体信息:也就是multisig.pb.go中定义的具体交易类型结构体 +// GetPayload 获取交易payload的结构体信息:也就是multisig.pb.go中定义的具体交易类型结构体 func (m *MultiSigType) GetPayload() types.Message { return &MultiSigAction{} } -//GetName 获取合约name +// GetName 获取合约name func (m *MultiSigType) GetName() string { return MultiSigX } -//GetTypeMap 获取处理具体交易的接口函数,也就是exec.go中的函数实现,去掉EXEC_ +// GetTypeMap 获取处理具体交易的接口函数,也就是exec.go中的函数实现,去掉EXEC_ func (m *MultiSigType) GetTypeMap() map[string]int32 { return map[string]int32{ "MultiSigAccCreate": ActionMultiSigAccCreate, @@ -61,7 +61,7 @@ func (m *MultiSigType) GetTypeMap() map[string]int32 { } } -//GetLogMap 获取具体执行Receiptlog对应的结构体: +// GetLogMap 获取具体执行Receiptlog对应的结构体: func (m *MultiSigType) GetLogMap() map[int64]*types.LogInfo { return map[int64]*types.LogInfo{ TyLogMultiSigAccCreate: {Ty: reflect.TypeOf(MultiSig{}), Name: "LogMultiSigAccCreate"}, @@ -84,7 +84,7 @@ func (m *MultiSigType) GetLogMap() map[int64]*types.LogInfo { } } -//DecodePayload 解码交易的Payload信息 +// DecodePayload 解码交易的Payload信息 func (m MultiSigType) DecodePayload(tx *types.Transaction) (types.Message, error) { var action MultiSigAction err := types.Decode(tx.Payload, &action) @@ -94,7 +94,7 @@ func (m MultiSigType) DecodePayload(tx *types.Transaction) (types.Message, error return &action, nil } -//ActionName 获取actionid对应的name +// ActionName 获取actionid对应的name func (m MultiSigType) ActionName(tx *types.Transaction) string { var g MultiSigAction err := types.Decode(tx.Payload, &g) diff --git a/plugin/dapp/multisig/wallet/exec.go b/plugin/dapp/multisig/wallet/exec.go index 0050fab029..21607da6ee 100644 --- a/plugin/dapp/multisig/wallet/exec.go +++ b/plugin/dapp/multisig/wallet/exec.go @@ -8,7 +8,7 @@ import ( "github.com/33cn/chain33/types" ) -//On_MultiSigAddresList 获取owner对应的多重签名地址列表 +// On_MultiSigAddresList 获取owner对应的多重签名地址列表 func (policy *multisigPolicy) On_MultiSigAddresList(req *types.ReqString) (types.Message, error) { //获取本钱包中记录的所有多重签名地址 if req.Data == "" { diff --git a/plugin/dapp/multisig/wallet/exec_test.go b/plugin/dapp/multisig/wallet/exec_test.go index 69de0bbdfb..d12e7b62ed 100644 --- a/plugin/dapp/multisig/wallet/exec_test.go +++ b/plugin/dapp/multisig/wallet/exec_test.go @@ -37,7 +37,7 @@ var ( GenAddr = "14KEKbYtKKQm4wMthSK9J4La4nAiidGozt" ) -//TestPrivkeyHex : +// TestPrivkeyHex : var TestPrivkeyHex = []string{ "0x06c0fa653c719275d1baa365c7bc0b9306447287499a715b541b930482eaa504", "0x4c8663cded61093af20339ae038b3c6bfa58a33e65874a655022f82eaf3f2fa0", @@ -89,7 +89,7 @@ func TestMultiSigAccount(t *testing.T) { testReplaceOwner(t, mocker, jrpcClient, multiSigAccAddr) } -//创建多重签名账户 +// 创建多重签名账户 func testAccCreateTx(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient) string { gen := mocker.GetGenesisKey() var params rpctypes.Query4Jrpc @@ -158,7 +158,7 @@ func testAccCreateTx(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jso return multiSigAccAddr } -//owner add AddrE +// owner add AddrE func testAddOwner(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() @@ -191,7 +191,7 @@ func testAddOwner(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsoncl assert.Equal(t, res4.Items[0].Weight, uint64(8)) } -//owner del AddrE +// owner del AddrE func testDelOwner(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() @@ -221,7 +221,7 @@ func testDelOwner(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsoncl assert.Equal(t, err, types.ErrNotFound) } -//ModifyOwnerWeight +// ModifyOwnerWeight func testModifyOwnerWeight(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() @@ -254,7 +254,7 @@ func testModifyOwnerWeight(t *testing.T, mocker *testnode.Chain33Mock, jrpcClien assert.Equal(t, res4.Items[0].Weight, uint64(30)) } -//testReplaceOwner owner AddrA replace by AddrE +// testReplaceOwner owner AddrA replace by AddrE func testReplaceOwner(t *testing.T, mocker *testnode.Chain33Mock, jrpcClient *jsonclient.JSONClient, multiSigAccAddr string) { gen := mocker.GetGenesisKey() diff --git a/plugin/dapp/multisig/wallet/multisig.go b/plugin/dapp/multisig/wallet/multisig.go index 97232513e1..c17bfd8fc8 100644 --- a/plugin/dapp/multisig/wallet/multisig.go +++ b/plugin/dapp/multisig/wallet/multisig.go @@ -187,7 +187,7 @@ func (policy *multisigPolicy) filterMultisigTxsFromBlock(tx *types.Transaction, } } -//需要区分执行的是add/Rollback +// 需要区分执行的是add/Rollback func (policy *multisigPolicy) saveMultiSigAccCreate(multiSig *mtypes.MultiSig, newbatch db.Batch, addOrRollback bool) { wallet := policy.getWalletOperate() @@ -218,7 +218,7 @@ func (policy *multisigPolicy) saveMultiSigAccCreate(multiSig *mtypes.MultiSig, n } } -//账户owner的add/del操作.需要区分add/del 交易 +// 账户owner的add/del操作.需要区分add/del 交易 func (policy *multisigPolicy) saveMultiSigOwnerAddOrDel(ownerOp *mtypes.ReceiptOwnerAddOrDel, newbatch db.Batch, addOrRollback bool) { wallet := policy.getWalletOperate() owner := ownerOp.Owner @@ -260,7 +260,7 @@ func (policy *multisigPolicy) saveMultiSigOwnerAddOrDel(ownerOp *mtypes.ReceiptO } } -//账户owner的mod/replace操作 +// 账户owner的mod/replace操作 func (policy *multisigPolicy) saveMultiSigOwnerModOrRep(ownerOp *mtypes.ReceiptOwnerModOrRep, newbatch db.Batch, addOrRollback bool) { wallet := policy.getWalletOperate() prevOwner := ownerOp.PrevOwner @@ -322,7 +322,7 @@ func (policy *multisigPolicy) saveMultiSigOwnerModOrRep(ownerOp *mtypes.ReceiptO } } -//AddOwnerAttr : 添加owmer属性 +// AddOwnerAttr : 添加owmer属性 func AddOwnerAttr(firstAdd bool, ownerAttrs *mtypes.OwnerAttrs, ownerAttr *mtypes.OwnerAttr, newbatch db.Batch) { if firstAdd { var firstownerAttrs mtypes.OwnerAttrs @@ -334,7 +334,7 @@ func AddOwnerAttr(firstAdd bool, ownerAttrs *mtypes.OwnerAttrs, ownerAttr *mtype batchSet(ownerAttrs, ownerAttr.OwnerAddr, newbatch) } -//DelOwnerAttr :删除owner属性 +// DelOwnerAttr :删除owner属性 func DelOwnerAttr(ownerAttrs *mtypes.OwnerAttrs, ownerAddr string, multiSigAddr string, newbatch db.Batch) { index, find := getOwnerAttr(ownerAttrs, multiSigAddr) if find { @@ -348,7 +348,7 @@ func DelOwnerAttr(ownerAttrs *mtypes.OwnerAttrs, ownerAddr string, multiSigAddr } } -//ModOwnerAttr :修改owner weight属性 +// ModOwnerAttr :修改owner weight属性 func ModOwnerAttr(ownerAttrs *mtypes.OwnerAttrs, ownerAddr string, multiSigAddr string, weight uint64, newbatch db.Batch) { index, find := getOwnerAttr(ownerAttrs, multiSigAddr) if find { @@ -357,14 +357,14 @@ func ModOwnerAttr(ownerAttrs *mtypes.OwnerAttrs, ownerAddr string, multiSigAddr } } -//batchSet : +// batchSet : func batchSet(ownerAttrs *mtypes.OwnerAttrs, addr string, newbatch db.Batch) { v := *ownerAttrs ownerAttrsbyte := types.Encode(&v) newbatch.Set(calcMultisigAddr(addr), ownerAttrsbyte) } -//delOwnerAttr : +// delOwnerAttr : func delOwnerAttr(ownerAttrs *mtypes.OwnerAttrs, index int) *mtypes.OwnerAttrs { ownerSize := len(ownerAttrs.Items) //删除第一个owner @@ -378,7 +378,7 @@ func delOwnerAttr(ownerAttrs *mtypes.OwnerAttrs, index int) *mtypes.OwnerAttrs { return ownerAttrs } -//addOwnerAttr : +// addOwnerAttr : func addOwnerAttr(ownerAttrs *mtypes.OwnerAttrs, ownerAttr *mtypes.OwnerAttr) *mtypes.OwnerAttrs { ownerAttrs.Items = append(ownerAttrs.Items, ownerAttr) return ownerAttrs diff --git a/plugin/dapp/multisig/wallet/multisig_store.go b/plugin/dapp/multisig/wallet/multisig_store.go index f0af7a873a..18be29b2ae 100644 --- a/plugin/dapp/multisig/wallet/multisig_store.go +++ b/plugin/dapp/multisig/wallet/multisig_store.go @@ -20,7 +20,7 @@ type multisigStore struct { *wcom.Store } -//获取指定owner拥有的多重签名地址 +// 获取指定owner拥有的多重签名地址 func (store *multisigStore) listOwnerAttrsByAddr(addr string) (*mtypes.OwnerAttrs, error) { if len(addr) == 0 { bizlog.Error("listMultisigAddrByOwnerAddr addr is nil") @@ -47,7 +47,7 @@ func (store *multisigStore) listOwnerAttrsByAddr(addr string) (*mtypes.OwnerAttr return &ownerAttrs, nil } -//获取本钱包地址拥有的所有多重签名地址 +// 获取本钱包地址拥有的所有多重签名地址 func (store *multisigStore) listOwnerAttrs() (*mtypes.OwnerAttrs, error) { list := store.NewListHelper() diff --git a/plugin/dapp/norm/executor/norm.go b/plugin/dapp/norm/executor/norm.go index ae62e1d156..6ffc1c13bd 100644 --- a/plugin/dapp/norm/executor/norm.go +++ b/plugin/dapp/norm/executor/norm.go @@ -20,7 +20,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Norm{})) diff --git a/plugin/dapp/norm/types/const.go b/plugin/dapp/norm/types/const.go index f519daa8f2..9333c7f344 100644 --- a/plugin/dapp/norm/types/const.go +++ b/plugin/dapp/norm/types/const.go @@ -4,7 +4,7 @@ package types -//norm action +// norm action const ( NormActionPut = 1 ) diff --git a/plugin/dapp/norm/types/norm.go b/plugin/dapp/norm/types/norm.go index 91763b1060..fdf3a04043 100644 --- a/plugin/dapp/norm/types/norm.go +++ b/plugin/dapp/norm/types/norm.go @@ -17,12 +17,12 @@ func init() { types.RegExec(NormX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(NormX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(NormX, NewType(cfg)) } diff --git a/plugin/dapp/oracle/executor/oracle.go b/plugin/dapp/oracle/executor/oracle.go index b6dcd9e6e7..0e8157ca21 100644 --- a/plugin/dapp/oracle/executor/oracle.go +++ b/plugin/dapp/oracle/executor/oracle.go @@ -22,7 +22,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&oracle{})) diff --git a/plugin/dapp/oracle/executor/query.go b/plugin/dapp/oracle/executor/query.go index 950a17d98d..3da4129d38 100644 --- a/plugin/dapp/oracle/executor/query.go +++ b/plugin/dapp/oracle/executor/query.go @@ -11,12 +11,12 @@ import ( oty "github.com/33cn/plugin/plugin/dapp/oracle/types" ) -//从statedb 读取原始数据 +// 从statedb 读取原始数据 func (o *oracle) Query_QueryOraclesByIDs(in *oty.QueryOracleInfos) (types.Message, error) { return getOracleLisByIDs(o.GetStateDB(), in) } -//通过状态查询ids +// 通过状态查询ids func (o *oracle) Query_QueryEventIDsByStatus(in *oty.QueryEventID) (types.Message, error) { eventIds, err := getEventIDListByStatus(o.GetLocalDB(), in.Status, in.EventID) if err != nil { @@ -26,7 +26,7 @@ func (o *oracle) Query_QueryEventIDsByStatus(in *oty.QueryEventID) (types.Messag return eventIds, nil } -//通过状态 和 地址查询 +// 通过状态 和 地址查询 func (o *oracle) Query_QueryEventIDsByAddrAndStatus(in *oty.QueryEventID) (types.Message, error) { eventIds, err := getEventIDListByAddrAndStatus(o.GetLocalDB(), in.Addr, in.Status, in.EventID) if err != nil { @@ -36,7 +36,7 @@ func (o *oracle) Query_QueryEventIDsByAddrAndStatus(in *oty.QueryEventID) (types return eventIds, nil } -//通过类型和状态查询 +// 通过类型和状态查询 func (o *oracle) Query_QueryEventIDsByTypeAndStatus(in *oty.QueryEventID) (types.Message, error) { eventIds, err := getEventIDListByTypeAndStatus(o.GetLocalDB(), in.Type, in.Status, in.EventID) if err != nil { diff --git a/plugin/dapp/oracle/types/oracle.pb.go b/plugin/dapp/oracle/types/oracle.pb.go index 20c1486e97..54eb4028aa 100644 --- a/plugin/dapp/oracle/types/oracle.pb.go +++ b/plugin/dapp/oracle/types/oracle.pb.go @@ -21,7 +21,7 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -//事件 +// 事件 type OracleStatus struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/oracle/types/table.go b/plugin/dapp/oracle/types/table.go index 6db0740a50..00346c510c 100644 --- a/plugin/dapp/oracle/types/table.go +++ b/plugin/dapp/oracle/types/table.go @@ -22,7 +22,7 @@ var opt = &table.Option{ Index: []string{"status", "addr_status", "type_status"}, } -//NewTable 新建表 +// NewTable 新建表 func NewTable(kvdb db.KV) *table.Table { rowmeta := NewOracleRow() table, err := table.NewTable(rowmeta, kvdb, opt) @@ -32,22 +32,22 @@ func NewTable(kvdb db.KV) *table.Table { return table } -//OracleRow table meta 结构 +// OracleRow table meta 结构 type OracleRow struct { *ReceiptOracle } -//NewOracleRow 新建一个meta 结构 +// NewOracleRow 新建一个meta 结构 func NewOracleRow() *OracleRow { return &OracleRow{ReceiptOracle: &ReceiptOracle{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存eventid) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存eventid) func (tx *OracleRow) CreateRow() *table.Row { return &table.Row{Data: &ReceiptOracle{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (tx *OracleRow) SetPayload(data types.Message) error { if txdata, ok := data.(*ReceiptOracle); ok { tx.ReceiptOracle = txdata @@ -56,7 +56,7 @@ func (tx *OracleRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (tx *OracleRow) Get(key string) ([]byte, error) { if key == "eventid" { return []byte(tx.EventID), nil diff --git a/plugin/dapp/oracle/types/types.go b/plugin/dapp/oracle/types/types.go index aae93403a3..cb1d4e996a 100644 --- a/plugin/dapp/oracle/types/types.go +++ b/plugin/dapp/oracle/types/types.go @@ -19,12 +19,12 @@ func init() { types.RegExec(OracleX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(OracleX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(OracleX, NewType(cfg)) } diff --git a/plugin/dapp/paracross/commands/paracross.go b/plugin/dapp/paracross/commands/paracross.go index 10eda74198..b3bfe98e5e 100644 --- a/plugin/dapp/paracross/commands/paracross.go +++ b/plugin/dapp/paracross/commands/paracross.go @@ -21,7 +21,7 @@ import ( "github.com/spf13/cobra" ) -//ParcCmd paracross cmd register +// ParcCmd paracross cmd register func ParcCmd() *cobra.Command { cmd := &cobra.Command{ Use: "para", @@ -162,7 +162,7 @@ func createAssetTx(cmd *cobra.Command, isWithdraw bool) (string, error) { return hex.EncodeToString(txHex), nil } -//CreateRawTransferCmd create raw transfer tx +// CreateRawTransferCmd create raw transfer tx func CreateRawTransferCmd() *cobra.Command { cmd := &cobra.Command{ Use: "transfer", @@ -190,7 +190,7 @@ func createTransfer(cmd *cobra.Command, args []string) { commands.CreateAssetTransfer(cmd, args, pt.ParaX) } -//CreateRawTransferToExecCmd create raw transfer to exec tx +// CreateRawTransferToExecCmd create raw transfer to exec tx func CreateRawTransferToExecCmd() *cobra.Command { cmd := &cobra.Command{ Use: "transfer_exec", @@ -218,7 +218,7 @@ func createTransferToExec(cmd *cobra.Command, args []string) { commands.CreateAssetSendToExec(cmd, args, pt.ParaX) } -//CreateRawWithdrawCmd create raw withdraw tx +// CreateRawWithdrawCmd create raw withdraw tx func CreateRawWithdrawCmd() *cobra.Command { cmd := &cobra.Command{ Use: "withdraw", diff --git a/plugin/dapp/paracross/executor/account.go b/plugin/dapp/paracross/executor/account.go index 0d2088d32a..00aa0554e6 100644 --- a/plugin/dapp/paracross/executor/account.go +++ b/plugin/dapp/paracross/executor/account.go @@ -13,7 +13,7 @@ import ( // 注: 在计算帐号地址时, 平行链paracross合约地址需要带上title前缀,才能表现出和主链一致, 但是现在不带, -//NewParaAccount create new paracross account +// NewParaAccount create new paracross account // 其中带{}, 都表示变量, 用需要用真实的地址, 符号代替 // 构建主链资产在平行链paracross帐号 // execName: user.p.{guodun}.paracross @@ -29,7 +29,7 @@ func NewParaAccount(cfg *types.Chain33Config, paraTitle, mainExecName, mainSymbo return account.NewAccountDB(cfg, paraExec, paraSymbol, db) } -//NewMainAccount create new Main account +// NewMainAccount create new Main account // 以后如果支持从平行链资产转移到主链, 构建平行链资产在主链的paracross帐号 // execName: paracross // symbol: user.p.{guodun}.coins.{guodun} user.p.{guodun}.token.{TEST} diff --git a/plugin/dapp/paracross/executor/action.go b/plugin/dapp/paracross/executor/action.go index 2555abbd69..6c71e23469 100644 --- a/plugin/dapp/paracross/executor/action.go +++ b/plugin/dapp/paracross/executor/action.go @@ -139,7 +139,7 @@ func checkCommitInfo(cfg *types.Chain33Config, commit *pt.ParacrossNodeStatus) e return nil } -//区块链中不能使用float类型 +// 区块链中不能使用float类型 func isCommitDone(nodes, mostSame int) bool { return 3*mostSame > 2*nodes } @@ -236,7 +236,7 @@ func makeDoneReceipt(cfg *types.Chain33Config, execMainHeight, execHeight int64, } } -//GetMostCommit ... +// GetMostCommit ... func GetMostCommit(commits [][]byte) (int, string) { stats := make(map[string]int) n := len(commits) @@ -258,7 +258,7 @@ func GetMostCommit(commits [][]byte) (int, string) { return most, hash } -//需要在ForkLoopCheckCommitTxDone后使用 +// 需要在ForkLoopCheckCommitTxDone后使用 func getMostResults(mostHash []byte, stat *pt.ParacrossHeightStatus) []byte { for i, hash := range stat.BlockDetails.BlockHashs { if bytes.Equal(mostHash, hash) { @@ -332,7 +332,7 @@ func (a *action) isValidSuperNode(addr string) error { return nil } -//相同的BlockHash,只保留一份数据 +// 相同的BlockHash,只保留一份数据 func updateCommitBlockHashs(stat *pt.ParacrossHeightStatus, commit *pt.ParacrossNodeStatus) { if stat.BlockDetails == nil { stat.BlockDetails = &pt.ParacrossStatusBlockDetails{} @@ -346,7 +346,7 @@ func updateCommitBlockHashs(stat *pt.ParacrossHeightStatus, commit *pt.Paracross stat.BlockDetails.TxResults = append(stat.BlockDetails.TxResults, commit.TxResult) } -//根据nodes过滤掉可能退出了的addrs +// 根据nodes过滤掉可能退出了的addrs func updateCommitAddrs(stat *pt.ParacrossHeightStatus, nodes map[string]struct{}) { details := &pt.ParacrossStatusDetails{} for i, addr := range stat.Details.Addrs { @@ -369,9 +369,9 @@ func updateSupervisionDetailsCommitAddrs(stat *pt.ParacrossHeightStatus, nodes m stat.SupervisionDetails = supervisionDetailsDetails } -//自共识分阶段使能,综合考虑挖矿奖励和共识分配奖励,判断是否自共识使能需要采用共识的高度,而不能采用当前区块高度a.height -//考虑自共识使能区块高度100,如果采用区块高度判断,则在100高度可能收到80~99的20条共识交易,这20条交易在100高度参与共识,则无奖励可分配,而且共识高度将是80而不是100 -//采用共识高度commit.Status.Height判断,则严格执行了产生奖励和分配奖励,且共识高度从100开始 +// 自共识分阶段使能,综合考虑挖矿奖励和共识分配奖励,判断是否自共识使能需要采用共识的高度,而不能采用当前区块高度a.height +// 考虑自共识使能区块高度100,如果采用区块高度判断,则在100高度可能收到80~99的20条共识交易,这20条交易在100高度参与共识,则无奖励可分配,而且共识高度将是80而不是100 +// 采用共识高度commit.Status.Height判断,则严格执行了产生奖励和分配奖励,且共识高度从100开始 func paraCheckSelfConsOn(cfg *types.Chain33Config, db dbm.KV, commit *pt.ParacrossNodeStatus) (bool, *types.Receipt, error) { if !cfg.IsDappFork(commit.Height, pt.ParaX, pt.ForkParaSelfConsStages) { return true, nil, nil @@ -454,7 +454,7 @@ func getValidAddrs(nodes map[string]struct{}, addrs []string) []string { return ret } -//get secp256 addr's bls pubkey +// get secp256 addr's bls pubkey func getAddrBlsPubKey(db dbm.KV, title, addr string) (string, error) { addrStat, err := getNodeAddr(db, title, addr) if err != nil { @@ -463,7 +463,7 @@ func getAddrBlsPubKey(db dbm.KV, title, addr string) (string, error) { return addrStat.BlsPubKey, nil } -//bls签名共识交易验证 大约平均耗时3ms (2~4ms) +// bls签名共识交易验证 大约平均耗时3ms (2~4ms) func (a *action) procBlsSign(nodesArry []string, commit *pt.ParacrossCommitAction) ([]string, error) { signAddrs := util.GetAddrsByBitMap(nodesArry, commit.Bls.AddrsMap) var pubs []string @@ -541,7 +541,7 @@ func (a *action) getValidCommitAddrs(commit *pt.ParacrossCommitAction, nodesMap return validAddrs, nil } -//共识commit msg 处理 +// 共识commit msg 处理 func (a *action) Commit(commit *pt.ParacrossCommitAction) (*types.Receipt, error) { cfg := a.api.GetConfig() //平行链侧,自共识未使能则不处理 @@ -709,7 +709,7 @@ func (a *action) proCommitMsg(commit *pt.ParacrossNodeStatus, nodes map[string]s return receipt, nil } -//分叉以前stat里面只记录了blockhash的信息,没有crossTxHash等信息,无法通过stat直接重构出mostCommitStatus +// 分叉以前stat里面只记录了blockhash的信息,没有crossTxHash等信息,无法通过stat直接重构出mostCommitStatus func (a *action) commitTxDone(nodeStatus *pt.ParacrossNodeStatus, stat *pt.ParacrossHeightStatus, titleStatus *pt.ParacrossStatus, nodes map[string]struct{}, supervisionNodes map[string]struct{}) (*types.Receipt, error) { receipt := &types.Receipt{} @@ -860,7 +860,7 @@ func (a *action) procCrossTxs(status *pt.ParacrossNodeStatus) (*types.Receipt, e return nil, nil } -//由于可能对当前块的共识交易进行处理,需要全部数据保存到statedb,通过tx获取数据无法处理当前块的场景 +// 由于可能对当前块的共识交易进行处理,需要全部数据保存到statedb,通过tx获取数据无法处理当前块的场景 func (a *action) loopCommitTxDone(title string) (*types.Receipt, error) { receipt := &types.Receipt{} @@ -926,7 +926,7 @@ func (a *action) checkCommitTxDone(stat *pt.ParacrossHeightStatus, nodes, superv return a.commitTxDoneByStat(stat, status, nodes, supervisionNodes) } -//只根据stat的信息在commitDone之后重构一个commitMostStatus做后续处理 +// 只根据stat的信息在commitDone之后重构一个commitMostStatus做后续处理 func (a *action) commitTxDoneByStat(stat *pt.ParacrossHeightStatus, titleStatus *pt.ParacrossStatus, nodes, supervisionNodes map[string]struct{}) (*types.Receipt, error) { clog.Debug("paracross.commitTxDoneByStat", "stat.title", stat.Title, "stat.height", stat.Height, "notes", len(nodes)) for i, v := range stat.Details.Addrs { @@ -995,7 +995,7 @@ func (a *action) commitTxDoneByStat(stat *pt.ParacrossHeightStatus, titleStatus return receipt, nil } -//主链共识跳跃条件: 仅支持主链共识初始高度为-1,也就是没有共识过,共识过不允许再跳跃 +// 主链共识跳跃条件: 仅支持主链共识初始高度为-1,也就是没有共识过,共识过不允许再跳跃 func (a *action) isAllowMainConsensJump(commit *pt.ParacrossNodeStatus, titleStatus *pt.ParacrossStatus) bool { cfg := a.api.GetConfig() if cfg.IsDappFork(a.exec.GetMainHeight(), pt.ParaX, pt.ForkLoopCheckCommitTxDone) { @@ -1007,7 +1007,7 @@ func (a *action) isAllowMainConsensJump(commit *pt.ParacrossNodeStatus, titleSta return false } -//平行链自共识无缝切换条件:1,平行链没有共识过,2:commit高度是大于自共识分叉高度且上一次共识的主链高度小于自共识分叉高度,保证只运行一次, +// 平行链自共识无缝切换条件:1,平行链没有共识过,2:commit高度是大于自共识分叉高度且上一次共识的主链高度小于自共识分叉高度,保证只运行一次, // 1. 分叉之前,开启过共识的平行链需要从1跳跃,没开启过的将使用新版本,从0开始发送,不用考虑从1跳跃的问题 // 2. 分叉之后,只有stage.blockHeight== commit.height,也就是stage起始高度时候允许跳跃 func (a *action) isAllowParaConsensJump(commit *pt.ParacrossNodeStatus, titleStatus *pt.ParacrossStatus) (bool, error) { @@ -1249,8 +1249,8 @@ func rollbackCrossTxNew(a *action, cross *types.Transaction, crossTxHash []byte) // //} -//无跨链交易高度列表是人为配置的,是确认的历史高度,是一种特殊处理,不会影响区块状态hash -//para.ignore.10-100.200-300 +// 无跨链交易高度列表是人为配置的,是确认的历史高度,是一种特殊处理,不会影响区块状态hash +// para.ignore.10-100.200-300 func isInIgnoreHeightList(str string, status *pt.ParacrossNodeStatus) (bool, error) { if len(str) <= 0 { return false, nil @@ -1322,10 +1322,10 @@ func isInHitHeightList(str string, status *pt.ParacrossNodeStatus) (bool, error) return false, nil } -//命中高度 -//s: para.hit.10.100, title=user.p.para. -//在有设置ParaCrossStatusBitMapVerLen的老版本之前,有些共识tx对应的区块没有跨链tx,分片查询很浪费时间,这里统计出来后, -//增加到配置文件里直接忽略相应高度。采用新的BitMap版本后,主链可以根据版本号判断有没有跨链tx,没有则直接退出,不需要再去区块中检查了。 +// 命中高度 +// s: para.hit.10.100, title=user.p.para. +// 在有设置ParaCrossStatusBitMapVerLen的老版本之前,有些共识tx对应的区块没有跨链tx,分片查询很浪费时间,这里统计出来后, +// 增加到配置文件里直接忽略相应高度。采用新的BitMap版本后,主链可以根据版本号判断有没有跨链tx,没有则直接退出,不需要再去区块中检查了。 func checkIsIgnoreHeight(heightList []string, status *pt.ParacrossNodeStatus) (bool, error) { if len(heightList) <= 0 { return false, nil diff --git a/plugin/dapp/paracross/executor/asset.go b/plugin/dapp/paracross/executor/asset.go index d2385ff800..56a759b979 100644 --- a/plugin/dapp/paracross/executor/asset.go +++ b/plugin/dapp/paracross/executor/asset.go @@ -17,21 +17,21 @@ import ( "github.com/pkg/errors" ) -//SymbolBty ... +// SymbolBty ... const SymbolBty = "bty" /* 资产 = assetExec + assetSymbol 唯一确定一个资产 - exec symbol tx.title=user.p.test1 tx.title=user.p.test2 -1. 主链上的资产: - coins bty transfer transfer - paracross user.p.test1.coins.fzm withdraw transfer + exec symbol tx.title=user.p.test1 tx.title=user.p.test2 + 1. 主链上的资产: + coins bty transfer transfer + paracross user.p.test1.coins.fzm withdraw transfer -2. 平行链上的资产: - user.p.test1.coins fzm transfer NAN - user.p.test1.paracross coins.bty withdraw NAN - user.p.test1.paracross paracross.user.p.test2.coins.cny withdraw NAN + 2. 平行链上的资产: + user.p.test1.coins fzm transfer NAN + user.p.test1.paracross coins.bty withdraw NAN + user.p.test1.paracross paracross.user.p.test2.coins.cny withdraw NAN 其中user.p.test1.paracross.paracross.user.p.test2.coins.cny资产解释: user.p.test1.paracross.是平行链paracross执行器, paracross.user.p.test2.coins.cny的paracross代表从主链的paracross转移过来的user.p.test2.coins.cny资产 @@ -63,7 +63,9 @@ func getCrossAction(transfer *pt.CrossAssetTransfer, txExecer string) (int64, er /* 修正原生执行器名字 - type realExec realSymbol + + type realExec realSymbol + coins+bty mainTransfer coins bty paracross+user.p.test1.coins.bty paraWithdraw coins bty user.p.test1.coins+bty paraTransfer coins bty @@ -137,7 +139,7 @@ func (a *action) crossAssetTransfer(transfer *pt.CrossAssetTransfer, act int64, } } -//主链先transfer, 然后平行链create asset, 如果平行链失败,主链再rollback +// 主链先transfer, 然后平行链create asset, 如果平行链失败,主链再rollback func (a *action) mainAssetTransfer(transfer *pt.CrossAssetTransfer, transferTx *types.Transaction) (*types.Receipt, error) { cfg := a.api.GetConfig() isPara := cfg.IsPara() @@ -148,7 +150,7 @@ func (a *action) mainAssetTransfer(transfer *pt.CrossAssetTransfer, transferTx * return a.execCreateAsset(transfer, transferTx) } -//平行链先销毁, 共识后主链再withdraw +// 平行链先销毁, 共识后主链再withdraw func (a *action) mainAssetWithdraw(withdraw *pt.CrossAssetTransfer, withdrawTx *types.Transaction) (*types.Receipt, error) { cfg := a.api.GetConfig() isPara := cfg.IsPara() @@ -159,7 +161,7 @@ func (a *action) mainAssetWithdraw(withdraw *pt.CrossAssetTransfer, withdrawTx * return a.execDestroyAsset(withdraw, withdrawTx) } -//平行链先转移, 共识后主链create asset +// 平行链先转移, 共识后主链create asset func (a *action) paraAssetTransfer(transfer *pt.CrossAssetTransfer, transferTx *types.Transaction) (*types.Receipt, error) { cfg := a.api.GetConfig() isPara := cfg.IsPara() @@ -171,7 +173,7 @@ func (a *action) paraAssetTransfer(transfer *pt.CrossAssetTransfer, transferTx * return a.execCreateAsset(transfer, transferTx) } -//平行链从主链提回, 先在主链处理,然后在平行链处理, 如果平行链执行失败,共识后主链再回滚 +// 平行链从主链提回, 先在主链处理,然后在平行链处理, 如果平行链执行失败,共识后主链再回滚 func (a *action) paraAssetWithdraw(withdraw *pt.CrossAssetTransfer, withdrawTx *types.Transaction) (*types.Receipt, error) { cfg := a.api.GetConfig() isPara := cfg.IsPara() @@ -221,7 +223,7 @@ func (a *action) execTransfer(transfer *pt.CrossAssetTransfer, transferTx *types return r, nil } -//withdraw是共识交易触发的,a.tx是共识交易, withdrawTx是最初提交的withdraw的tx +// withdraw是共识交易触发的,a.tx是共识交易, withdrawTx是最初提交的withdraw的tx func (a *action) execWithdraw(withdraw *pt.CrossAssetTransfer, withdrawTx *types.Transaction) (*types.Receipt, error) { cfg := a.api.GetConfig() accDB, err := a.createAccount(cfg, a.db, withdraw.AssetExec, withdraw.AssetSymbol) @@ -254,9 +256,9 @@ func (a *action) execWithdraw(withdraw *pt.CrossAssetTransfer, withdrawTx *types return r, nil } -//主链Alice的token转移到user.p.bb.平行链,在平行链上表示为mavl-paracross-token.symbol-Addr(Alice),这里并没有放在Addr(user.p.bb.paracross)子账号下 -//平行链转移到主链的token在主链表示为mavl-paracross-user.p.aa.token.symbol-exec-Addr(Alice),再转移到另一个user.p.bb.平行链,需要先transfer到paracross执行器下 -//在平行链bb上铸造新币,表示为mavl-paracross-paracross.user.p.aa.token.symbol-exec-Addr(Alice),第二个paracross代表在主链原生执行器为paracross +// 主链Alice的token转移到user.p.bb.平行链,在平行链上表示为mavl-paracross-token.symbol-Addr(Alice),这里并没有放在Addr(user.p.bb.paracross)子账号下 +// 平行链转移到主链的token在主链表示为mavl-paracross-user.p.aa.token.symbol-exec-Addr(Alice),再转移到另一个user.p.bb.平行链,需要先transfer到paracross执行器下 +// 在平行链bb上铸造新币,表示为mavl-paracross-paracross.user.p.aa.token.symbol-exec-Addr(Alice),第二个paracross代表在主链原生执行器为paracross func (a *action) createParaAccount(cross *pt.CrossAssetTransfer, crossTx *types.Transaction) (*account.DB, error) { cfg := a.api.GetConfig() paraTitle, err := getTitleFrom(crossTx.Execer) @@ -306,7 +308,7 @@ func (a *action) execDestroyAsset(withdraw *pt.CrossAssetTransfer, withdrawTx *t return r, nil } -//旧的接口,只有主链向平行链转移 +// 旧的接口,只有主链向平行链转移 func (a *action) assetTransfer(transfer *types.AssetsTransfer) (*types.Receipt, error) { tr := &pt.CrossAssetTransfer{ AssetSymbol: transfer.Cointoken, @@ -318,7 +320,7 @@ func (a *action) assetTransfer(transfer *types.AssetsTransfer) (*types.Receipt, return a.mainAssetTransfer(tr, a.tx) } -//旧的接口,只有主链从平行链转移 +// 旧的接口,只有主链从平行链转移 func (a *action) assetWithdraw(withdraw *types.AssetsWithdraw, withdrawTx *types.Transaction) (*types.Receipt, error) { tr := &pt.CrossAssetTransfer{ AssetExec: withdraw.ExecName, @@ -353,7 +355,7 @@ func (a *action) assetTransferRollback(transfer *pt.CrossAssetTransfer, transfer return nil, nil } -//平行链从主链withdraw在平行链执行失败,主链恢复数据,主链执行 +// 平行链从主链withdraw在平行链执行失败,主链恢复数据,主链执行 func (a *action) paraAssetWithdrawRollback(wtw *pt.CrossAssetTransfer, withdrawTx *types.Transaction) (*types.Receipt, error) { cfg := a.api.GetConfig() isPara := cfg.IsPara() @@ -387,9 +389,9 @@ func (a *action) createAccount(cfg *types.Chain33Config, db db.KV, exec, symbol return account.NewAccountDB(cfg, exec, symbol, db) } -//对于旧的assetTransfer,assetWithdraw资产转移接口,没有填AssetExec,这里只支持coins,如果主链是coinsx执行器,则旧接口会失败,需要用新接口。 -//新接口必须填AssetExec,主链和平行链从跨链交易资产参数上会保持一致,目的资产不依赖目标的toml配置文件 -//比如主链是coinsx 平行链也会铸造coinsx.bty资产,withdraw到主链也是coinsx +// 对于旧的assetTransfer,assetWithdraw资产转移接口,没有填AssetExec,这里只支持coins,如果主链是coinsx执行器,则旧接口会失败,需要用新接口。 +// 新接口必须填AssetExec,主链和平行链从跨链交易资产参数上会保持一致,目的资产不依赖目标的toml配置文件 +// 比如主链是coinsx 平行链也会铸造coinsx.bty资产,withdraw到主链也是coinsx func adaptNullAssetExec(transfer *pt.CrossAssetTransfer) { if transfer.AssetSymbol == "" { transfer.AssetExec = "coins" diff --git a/plugin/dapp/paracross/executor/bindminer.go b/plugin/dapp/paracross/executor/bindminer.go index 32b352cbc8..9965e02bd0 100644 --- a/plugin/dapp/paracross/executor/bindminer.go +++ b/plugin/dapp/paracross/executor/bindminer.go @@ -14,7 +14,7 @@ const ( opModify = 3 ) -//从内存中获取bin状态的miner list +// 从内存中获取bin状态的miner list func (a *action) getBindAddrs(nodes []string, statusHeight int64) (bool, map[string][]*pt.ParaBindMinerInfo, error) { nodeBinders := make(map[string][]*pt.ParaBindMinerInfo) var foundBinder bool diff --git a/plugin/dapp/paracross/executor/db.go b/plugin/dapp/paracross/executor/db.go index 10aa7ac2da..dede3b577c 100644 --- a/plugin/dapp/paracross/executor/db.go +++ b/plugin/dapp/paracross/executor/db.go @@ -54,7 +54,7 @@ func saveTitleHeight(db dbm.KV, key []byte, heightStatus types.Message /* height return db.Set(key, val) } -//GetBlock get block detail by block hash +// GetBlock get block detail by block hash func GetBlock(api client.QueueProtocolAPI, blockHash []byte) (*types.BlockDetail, error) { blockDetails, err := api.GetBlockByHashes(&types.ReqHashes{Hashes: [][]byte{blockHash}}) if err != nil { @@ -113,7 +113,7 @@ func isNotFound(err error) bool { return false } -//GetTx get tx by tx hash +// GetTx get tx by tx hash func GetTx(api client.QueueProtocolAPI, txHash []byte) (*types.TransactionDetail, error) { txs, err := api.GetTransactionByHash(&types.ReqHashes{Hashes: [][]byte{txHash}}) if err != nil { diff --git a/plugin/dapp/paracross/executor/exec.go b/plugin/dapp/paracross/executor/exec.go index 6b88e4f997..0c848787b1 100644 --- a/plugin/dapp/paracross/executor/exec.go +++ b/plugin/dapp/paracross/executor/exec.go @@ -11,7 +11,7 @@ import ( pt "github.com/33cn/plugin/plugin/dapp/paracross/types" ) -//Exec_Commit consensus commit tx exec process +// Exec_Commit consensus commit tx exec process func (e *Paracross) Exec_Commit(payload *pt.ParacrossCommitAction, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(e, tx) receipt, err := a.Commit(payload) @@ -22,7 +22,7 @@ func (e *Paracross) Exec_Commit(payload *pt.ParacrossCommitAction, tx *types.Tra return receipt, nil } -//Exec_AssetTransfer asset transfer exec process +// Exec_AssetTransfer asset transfer exec process func (e *Paracross) Exec_AssetTransfer(payload *types.AssetsTransfer, tx *types.Transaction, index int) (*types.Receipt, error) { clog.Debug("Paracross.Exec", "transfer", "") _, err := e.checkTxGroup(tx, index) @@ -39,7 +39,7 @@ func (e *Paracross) Exec_AssetTransfer(payload *types.AssetsTransfer, tx *types. return receipt, nil } -//Exec_AssetWithdraw asset withdraw exec process +// Exec_AssetWithdraw asset withdraw exec process func (e *Paracross) Exec_AssetWithdraw(payload *types.AssetsWithdraw, tx *types.Transaction, index int) (*types.Receipt, error) { _, err := e.checkTxGroup(tx, index) if err != nil { @@ -55,7 +55,7 @@ func (e *Paracross) Exec_AssetWithdraw(payload *types.AssetsWithdraw, tx *types. return receipt, nil } -//Exec_CrossAssetTransfer parallel chain asset transfer exec process +// Exec_CrossAssetTransfer parallel chain asset transfer exec process func (e *Paracross) Exec_CrossAssetTransfer(payload *pt.CrossAssetTransfer, tx *types.Transaction, index int) (*types.Receipt, error) { _, err := e.checkTxGroup(tx, index) if err != nil { @@ -71,7 +71,7 @@ func (e *Paracross) Exec_CrossAssetTransfer(payload *pt.CrossAssetTransfer, tx * return receipt, nil } -//Exec_Miner miner tx exec process +// Exec_Miner miner tx exec process func (e *Paracross) Exec_Miner(payload *pt.ParacrossMinerAction, tx *types.Transaction, index int) (*types.Receipt, error) { if index != 0 && payload.AddIssueCoins <= 0 { return nil, pt.ErrParaMinerBaseIndex @@ -84,49 +84,49 @@ func (e *Paracross) Exec_Miner(payload *pt.ParacrossMinerAction, tx *types.Trans return a.Miner(payload) } -//Exec_Transfer exec asset transfer process +// Exec_Transfer exec asset transfer process func (e *Paracross) Exec_Transfer(payload *types.AssetsTransfer, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(e, tx) return a.Transfer(payload, tx, index) } -//Exec_Withdraw exec asset withdraw +// Exec_Withdraw exec asset withdraw func (e *Paracross) Exec_Withdraw(payload *types.AssetsWithdraw, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(e, tx) return a.Withdraw(payload, tx, index) } -//Exec_TransferToExec exec transfer asset +// Exec_TransferToExec exec transfer asset func (e *Paracross) Exec_TransferToExec(payload *types.AssetsTransferToExec, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(e, tx) return a.TransferToExec(payload, tx, index) } -//Exec_NodeConfig exec super node config +// Exec_NodeConfig exec super node config func (e *Paracross) Exec_NodeConfig(payload *pt.ParaNodeAddrConfig, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(e, tx) return a.NodeConfig(payload) } -//Exec_NodeGroupConfig node group config process +// Exec_NodeGroupConfig node group config process func (e *Paracross) Exec_NodeGroupConfig(payload *pt.ParaNodeGroupConfig, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(e, tx) return a.NodeGroupConfig(payload) } -//Exec_SelfStageConfig node group config process +// Exec_SelfStageConfig node group config process func (e *Paracross) Exec_SelfStageConfig(payload *pt.ParaStageConfig, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(e, tx) return a.SelfStageConfig(payload) } -//Exec_ParaBindMiner node group config process +// Exec_ParaBindMiner node group config process func (e *Paracross) Exec_ParaBindMiner(payload *pt.ParaBindMinerCmd, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(e, tx) return a.bindMiner(payload) } -//Exec_SupervisionNodeConfig exec Supervision node config +// Exec_SupervisionNodeConfig exec Supervision node config func (e *Paracross) Exec_SupervisionNodeConfig(payload *pt.ParaNodeGroupConfig, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(e, tx) return a.SupervisionNodeConfig(payload) diff --git a/plugin/dapp/paracross/executor/exec_del_local.go b/plugin/dapp/paracross/executor/exec_del_local.go index d437e5d1b3..39a77973db 100644 --- a/plugin/dapp/paracross/executor/exec_del_local.go +++ b/plugin/dapp/paracross/executor/exec_del_local.go @@ -10,7 +10,7 @@ import ( pt "github.com/33cn/plugin/plugin/dapp/paracross/types" ) -//ExecDelLocal_Commit consensus commit tx del local db process +// ExecDelLocal_Commit consensus commit tx del local db process func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { var set types.LocalDBSet cfg := e.GetAPI().GetConfig() @@ -158,7 +158,7 @@ func (e *Paracross) ExecDelLocal_SupervisionNodeConfig(payload *pt.ParaNodeGroup return &set, nil } -//ExecDelLocal_AssetTransfer asset transfer del local db process +// ExecDelLocal_AssetTransfer asset transfer del local db process func (e *Paracross) ExecDelLocal_AssetTransfer(payload *types.AssetsTransfer, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { var set types.LocalDBSet @@ -173,12 +173,12 @@ func (e *Paracross) ExecDelLocal_AssetTransfer(payload *types.AssetsTransfer, tx return &set, nil } -//ExecDelLocal_AssetWithdraw asset withdraw local db process +// ExecDelLocal_AssetWithdraw asset withdraw local db process func (e *Paracross) ExecDelLocal_AssetWithdraw(payload *types.AssetsWithdraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return nil, nil } -//ExecDelLocal_CrossAssetTransfer asset transfer del local db process +// ExecDelLocal_CrossAssetTransfer asset transfer del local db process func (e *Paracross) ExecDelLocal_CrossAssetTransfer(payload *pt.CrossAssetTransfer, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { var set types.LocalDBSet r, err := e.initLocalAssetTransfer(tx, true, nil) @@ -190,7 +190,7 @@ func (e *Paracross) ExecDelLocal_CrossAssetTransfer(payload *pt.CrossAssetTransf return &set, nil } -//ExecDelLocal_Miner miner tx del local db process +// ExecDelLocal_Miner miner tx del local db process func (e *Paracross) ExecDelLocal_Miner(payload *pt.ParacrossMinerAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if index != 0 { return nil, pt.ErrParaMinerBaseIndex @@ -202,22 +202,22 @@ func (e *Paracross) ExecDelLocal_Miner(payload *pt.ParacrossMinerAction, tx *typ return &set, nil } -//ExecDelLocal_Transfer asset transfer del local process +// ExecDelLocal_Transfer asset transfer del local process func (e *Paracross) ExecDelLocal_Transfer(payload *types.AssetsTransfer, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return nil, nil } -//ExecDelLocal_Withdraw asset withdraw del local db process +// ExecDelLocal_Withdraw asset withdraw del local db process func (e *Paracross) ExecDelLocal_Withdraw(payload *types.AssetsWithdraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return nil, nil } -//ExecDelLocal_TransferToExec asset transfer to exec del local db process +// ExecDelLocal_TransferToExec asset transfer to exec del local db process func (e *Paracross) ExecDelLocal_TransferToExec(payload *types.AssetsTransferToExec, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return nil, nil } -//ExecDelLocal_SelfStageConfig transfer asset to exec local db process +// ExecDelLocal_SelfStageConfig transfer asset to exec local db process func (e *Paracross) ExecDelLocal_SelfStageConfig(payload *pt.ParaStageConfig, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return e.execAutoDelLocal(tx, receiptData) } diff --git a/plugin/dapp/paracross/executor/exec_local.go b/plugin/dapp/paracross/executor/exec_local.go index 51445713b5..8975b3c006 100644 --- a/plugin/dapp/paracross/executor/exec_local.go +++ b/plugin/dapp/paracross/executor/exec_local.go @@ -15,7 +15,7 @@ import ( pt "github.com/33cn/plugin/plugin/dapp/paracross/types" ) -//ExecLocal_Commit commit tx local db process +// ExecLocal_Commit commit tx local db process func (e *Paracross) ExecLocal_Commit(payload *pt.ParacrossCommitAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { var set types.LocalDBSet cfg := e.GetAPI().GetConfig() @@ -56,7 +56,7 @@ func (e *Paracross) ExecLocal_Commit(payload *pt.ParacrossCommitAction, tx *type return &set, nil } -//ExecLocal_NodeConfig node config add process +// ExecLocal_NodeConfig node config add process func (e *Paracross) ExecLocal_NodeConfig(payload *pt.ParaNodeAddrConfig, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { var set types.LocalDBSet cfg := e.GetAPI().GetConfig() @@ -105,7 +105,7 @@ func (e *Paracross) ExecLocal_NodeConfig(payload *pt.ParaNodeAddrConfig, tx *typ return &set, nil } -//ExecLocal_NodeGroupConfig node group config add process +// ExecLocal_NodeGroupConfig node group config add process func (e *Paracross) ExecLocal_NodeGroupConfig(payload *pt.ParaNodeGroupConfig, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { var set types.LocalDBSet for _, log := range receiptData.Logs { @@ -162,7 +162,7 @@ func (e *Paracross) ExecLocal_SupervisionNodeConfig(payload *pt.ParaNodeGroupCon return &set, nil } -//ExecLocal_AssetTransfer asset transfer local proc +// ExecLocal_AssetTransfer asset transfer local proc func (e *Paracross) ExecLocal_AssetTransfer(payload *types.AssetsTransfer, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { var set types.LocalDBSet @@ -181,12 +181,12 @@ func (e *Paracross) ExecLocal_AssetTransfer(payload *types.AssetsTransfer, tx *t return &set, nil } -//ExecLocal_AssetWithdraw asset withdraw process +// ExecLocal_AssetWithdraw asset withdraw process func (e *Paracross) ExecLocal_AssetWithdraw(payload *types.AssetsWithdraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return nil, nil } -//ExecLocal_CrossAssetTransfer asset transfer local proc +// ExecLocal_CrossAssetTransfer asset transfer local proc func (e *Paracross) ExecLocal_CrossAssetTransfer(payload *pt.CrossAssetTransfer, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { var set types.LocalDBSet cfg := e.GetAPI().GetConfig() @@ -250,9 +250,9 @@ func setMinerTxResult(cfg *types.Chain33Config, payload *pt.ParacrossMinerAction return nil } -//带版本号编码的bitmap,版本号占4bit位,除去版本号位,最高位为跨链交易个数,后面的则是交易结果bitmap -//比如00011110, 版本号为0001,1110的最高位1索引为3,代表后面3个交易,三个交易110代表第0个交易是失败的,其余的是ok的 -//如果没有数量表示,在所有跨链交易都是失败的时候,返回的是个空值,无法区分是失败还是无交易 +// 带版本号编码的bitmap,版本号占4bit位,除去版本号位,最高位为跨链交易个数,后面的则是交易结果bitmap +// 比如00011110, 版本号为0001,1110的最高位1索引为3,代表后面3个交易,三个交易110代表第0个交易是失败的,其余的是ok的 +// 如果没有数量表示,在所有跨链交易都是失败的时候,返回的是个空值,无法区分是失败还是无交易 func getCrossAssetTxBitMap(crossAssetTxHashs, allTxHashs [][]byte, receipts []*types.ReceiptData) string { rst := pt.ParaCrossStatusBitMapVer1 if len(crossAssetTxHashs) > 0 { @@ -315,7 +315,7 @@ func setMinerTxResultFork(cfg *types.Chain33Config, status *pt.ParacrossNodeStat return nil } -//ExecLocal_Miner miner tx local db process +// ExecLocal_Miner miner tx local db process func (e *Paracross) ExecLocal_Miner(payload *pt.ParacrossMinerAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { if index != 0 { return nil, pt.ErrParaMinerBaseIndex @@ -350,17 +350,17 @@ func (e *Paracross) ExecLocal_Transfer(payload *types.AssetsTransfer, tx *types. return nil, nil } -//ExecLocal_Withdraw asset withdraw local db process +// ExecLocal_Withdraw asset withdraw local db process func (e *Paracross) ExecLocal_Withdraw(payload *types.AssetsWithdraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return nil, nil } -//ExecLocal_TransferToExec transfer asset to exec local db process +// ExecLocal_TransferToExec transfer asset to exec local db process func (e *Paracross) ExecLocal_TransferToExec(payload *types.AssetsTransferToExec, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return nil, nil } -//ExecLocal_SelfStageConfig transfer asset to exec local db process +// ExecLocal_SelfStageConfig transfer asset to exec local db process func (e *Paracross) ExecLocal_SelfStageConfig(payload *pt.ParaStageConfig, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return e.execAutoLocalStage(tx, receiptData, index) } diff --git a/plugin/dapp/paracross/executor/filtertxs.go b/plugin/dapp/paracross/executor/filtertxs.go index 91513b9faa..1a105d7d88 100644 --- a/plugin/dapp/paracross/executor/filtertxs.go +++ b/plugin/dapp/paracross/executor/filtertxs.go @@ -14,9 +14,9 @@ import ( pt "github.com/33cn/plugin/plugin/dapp/paracross/types" ) -//1,如果全部是paracross的,主链成功会ExecOk,如果有一个不成功,全部回退回PACK,后面检查TyLogErr,OK意味着全部成功 -//2,如果是paracross+other, other的是PACK,如果有一个是OK,那意味着全部OK,如果全部是PACK,检查TyLogErr -//3,如果是全部other,全部是PACK +// 1,如果全部是paracross的,主链成功会ExecOk,如果有一个不成功,全部回退回PACK,后面检查TyLogErr,OK意味着全部成功 +// 2,如果是paracross+other, other的是PACK,如果有一个是OK,那意味着全部OK,如果全部是PACK,检查TyLogErr +// 3,如果是全部other,全部是PACK func checkReceiptExecOk(receipt *types.ReceiptData) bool { if receipt.Ty == types.ExecOk { return true @@ -30,12 +30,12 @@ func checkReceiptExecOk(receipt *types.ReceiptData) bool { return true } -//1. 如果涉及跨链合约,如果有超过两条平行链的交易被判定为失败,交易组会执行不成功,也不PACK。(这样的情况下,主链交易一定会执行不成功,最终也不会进到block里面) -//2. 跨链合约交易组,要么是paracross+user.p.xx.paracross组合,要么全是user.p.xx.paracross组合,后面是资产转移 -//3. 如果交易组有一个ExecOk,主链上的交易都是ok的,可以全部打包 -//4. 不论是否涉及跨链合约, 不同用途的tx打到一个group里面,如果主链交易有失败,平行链也不会执行,也需要排除掉 -//5. 如果全部是ExecPack,有两种情况,一是交易组所有交易都是平行链交易,另一是主链有交易失败而打包了的交易,需要检查LogErr,如果有错,全部不打包 -//经para filter之后, 交易组会存在如下几种tx: +// 1. 如果涉及跨链合约,如果有超过两条平行链的交易被判定为失败,交易组会执行不成功,也不PACK。(这样的情况下,主链交易一定会执行不成功,最终也不会进到block里面) +// 2. 跨链合约交易组,要么是paracross+user.p.xx.paracross组合,要么全是user.p.xx.paracross组合,后面是资产转移 +// 3. 如果交易组有一个ExecOk,主链上的交易都是ok的,可以全部打包 +// 4. 不论是否涉及跨链合约, 不同用途的tx打到一个group里面,如果主链交易有失败,平行链也不会执行,也需要排除掉 +// 5. 如果全部是ExecPack,有两种情况,一是交易组所有交易都是平行链交易,另一是主链有交易失败而打包了的交易,需要检查LogErr,如果有错,全部不打包 +// 经para filter之后, 交易组会存在如下几种tx: // 1, 主链 paracross + 平行链 user.p.xx.paracross 跨链兑换合约 // 2, 主链 paracross + 平行链 user.p.xx.other 混合交易组合 // 3, 主链 other + 平行链 user.p.xx.paracross 混合交易组合约 @@ -43,8 +43,8 @@ func checkReceiptExecOk(receipt *types.ReceiptData) bool { // 5, 主链+平行链 user.p.xx.paracross 交易组 混合跨链资产转移 // 6, 平行链 user.p.xx.paracross + user.p.xx.other 混合平行链组合 // 7, 平行链 all user.p.xx.other 混合平行链组合 -///// 分叉以后只考虑平行链交易组全部是平行链tx,没有主链tx -//经para filter之后, 交易组会存在如下几种tx: +// /// 分叉以后只考虑平行链交易组全部是平行链tx,没有主链tx +// 经para filter之后, 交易组会存在如下几种tx: // 1, 主链+平行链 user.p.xx.paracross 交易组 混合跨链资产转移 paracross主链执行成功 // 2, 平行链 user.p.xx.paracross + user.p.xx.other 混合平行链组合 paracross主链执行成功 // 3, 平行链 user.p.xx.other 交易组 混合平行链组合 other主链pack @@ -80,7 +80,7 @@ func filterParaTxGroup(cfg *types.Chain33Config, tx *types.Transaction, allTxs [ return retTxs, endIdx } -//FilterTxsForPara include some main tx in tx group before ForkParacrossCommitTx +// FilterTxsForPara include some main tx in tx group before ForkParacrossCommitTx func FilterTxsForPara(cfg *types.Chain33Config, main *types.ParaTxDetail) []*types.Transaction { cfgPara := types.ConfSub(cfg, pt.ParaX) discardTxs := cfgPara.GStrList("discardTxs") @@ -161,7 +161,7 @@ func FilterParaCrossAssetTxHashes(txs []*types.Transaction) ([][]byte, error) { return txHashs, nil } -//经para filter之后, 交易组会存在如下几种tx: +// 经para filter之后, 交易组会存在如下几种tx: // 1, 主链 paracross + 平行链 user.p.xx.paracross 跨链兑换合约 // 2, 主链 paracross + 平行链 user.p.xx.other 混合交易组合 // 3, 主链 other + 平行链 user.p.xx.paracross 混合交易组合 @@ -200,7 +200,7 @@ func crossTxGroupProc(title string, txs []*types.Transaction, index int) ([]*typ } -//FilterParaMainCrossTxHashes ForkParacrossCommitTx之前允许txgroup里面有main chain tx的跨链 +// FilterParaMainCrossTxHashes ForkParacrossCommitTx之前允许txgroup里面有main chain tx的跨链 func FilterParaMainCrossTxHashes(title string, txs []*types.Transaction) [][]byte { var crossTxHashs [][]byte //跨链tx 必须是paracross合约且user.p.打头, user.p.xx.的非paracross合约不是跨链 @@ -223,7 +223,7 @@ func FilterParaMainCrossTxHashes(title string, txs []*types.Transaction) [][]byt } -//CalcTxHashsHash 计算几个txhash的hash值 作校验使用 +// CalcTxHashsHash 计算几个txhash的hash值 作校验使用 func CalcTxHashsHash(txHashs [][]byte) []byte { if len(txHashs) == 0 { return nil diff --git a/plugin/dapp/paracross/executor/kv.go b/plugin/dapp/paracross/executor/kv.go index dfe8a440cd..fbdb179901 100644 --- a/plugin/dapp/paracross/executor/kv.go +++ b/plugin/dapp/paracross/executor/kv.go @@ -199,30 +199,30 @@ func calcLocalNodeGroupAllPrefix() []byte { /////bind miner -//统计共识节点绑定挖矿地址总数量 -//key: prefix-nodeAddr val: bindTotalCount +// 统计共识节点绑定挖矿地址总数量 +// key: prefix-nodeAddr val: bindTotalCount func calcParaNodeBindMinerCount(node string) []byte { return []byte(fmt.Sprintf(paraBindMinderNode+"%s", node)) } -//记录共识节点某一索引绑定的挖矿地址,一一对应,以此地址获取更详细信息 -//key: prefix-nodeAddr-index val:bindMinerAddr +// 记录共识节点某一索引绑定的挖矿地址,一一对应,以此地址获取更详细信息 +// key: prefix-nodeAddr-index val:bindMinerAddr func calcParaNodeBindMinerIndex(node string, index int64) []byte { return []byte(fmt.Sprintf(paraBindMinderNode+"%s-%d", node, index)) } -//记录node和miner bind详细信息 -//key: prefix-nodeAddr-miner val:miner detail info +// 记录node和miner bind详细信息 +// key: prefix-nodeAddr-miner val:miner detail info func calcParaBindMinerAddr(node, miner string) []byte { return []byte(fmt.Sprintf(paraBindMinderNode+"%s-%s", node, address.FormatAddrKey(miner))) } -//key: prefix-minerAddr val: node list +// key: prefix-minerAddr val: node list func calcParaMinerBindNodeList(miner string) []byte { return []byte(fmt.Sprintf(paraBindMinderAddr+"%s", address.FormatAddrKey(miner))) } -/////supervision +// ///supervision func calcParaSupervisionNodeGroupAddrsKey(title string) []byte { return []byte(fmt.Sprintf(paraSupervisionNodes+"%s", title)) } diff --git a/plugin/dapp/paracross/executor/miner.go b/plugin/dapp/paracross/executor/miner.go index 22c53d7d78..34baed00ac 100644 --- a/plugin/dapp/paracross/executor/miner.go +++ b/plugin/dapp/paracross/executor/miner.go @@ -11,9 +11,9 @@ import ( "github.com/pkg/errors" ) -//当前miner tx不需要校验上一个区块的衔接性,因为tx就是本节点发出,高度,preHash等都在本区块里面的blockchain做了校验 -//note: 平行链的Miner从Height=1开始, 创世区块不挖矿 -//因为bug原因,支持手动增发一部分coin到执行器地址,这部分coin不会对现有账户产生影响。因为转账到合约下的coin,同时会存到合约子账户下 +// 当前miner tx不需要校验上一个区块的衔接性,因为tx就是本节点发出,高度,preHash等都在本区块里面的blockchain做了校验 +// note: 平行链的Miner从Height=1开始, 创世区块不挖矿 +// 因为bug原因,支持手动增发一部分coin到执行器地址,这部分coin不会对现有账户产生影响。因为转账到合约下的coin,同时会存到合约子账户下 func (a *action) Miner(miner *pt.ParacrossMinerAction) (*types.Receipt, error) { cfg := a.api.GetConfig() //增发coin diff --git a/plugin/dapp/paracross/executor/minerrewards/nomal.go b/plugin/dapp/paracross/executor/minerrewards/nomal.go index e7a38c8bff..392fc1a3d6 100644 --- a/plugin/dapp/paracross/executor/minerrewards/nomal.go +++ b/plugin/dapp/paracross/executor/minerrewards/nomal.go @@ -11,7 +11,7 @@ func init() { register("normal", &normal{}) } -//获取配置的奖励数值 +// 获取配置的奖励数值 func (n *normal) GetConfigReward(cfg *types.Chain33Config, height int64) (int64, int64, int64) { coinReward := cfg.MGInt("mver.consensus.paracross.coinReward", height) fundReward := cfg.MGInt("mver.consensus.paracross.coinDevFund", height) @@ -35,7 +35,7 @@ func (n *normal) GetConfigReward(cfg *types.Chain33Config, height int64) (int64, return coinReward, fundReward, coinBaseReward } -//奖励矿工算法 +// 奖励矿工算法 func (n *normal) RewardMiners(cfg *types.Chain33Config, coinReward int64, miners []string, height int64) ([]*pt.ParaMinerReward, int64) { //找零 var change int64 diff --git a/plugin/dapp/paracross/executor/paracross.go b/plugin/dapp/paracross/executor/paracross.go index 60bd3d0af9..35c08bb357 100644 --- a/plugin/dapp/paracross/executor/paracross.go +++ b/plugin/dapp/paracross/executor/paracross.go @@ -29,20 +29,20 @@ type Paracross struct { drivers.DriverBase } -//Init paracross exec register +// Init paracross exec register func Init(name string, cfg *types.Chain33Config, sub []byte) { drivers.Register(cfg, GetName(), newParacross, cfg.GetDappFork(driverName, "Enable")) InitExecType() setPrefix() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Paracross{})) } -//GetName return paracross name +// GetName return paracross name func GetName() string { return newParacross().GetName() } @@ -106,7 +106,7 @@ func (c *Paracross) saveLocalParaTxs(tx *types.Transaction, isDel bool) (*types. } -//无法获取到commit tx信息,从commitDone 结构里面构建 +// 无法获取到commit tx信息,从commitDone 结构里面构建 func (c *Paracross) saveLocalParaTxsFork(commitDone *pt.ReceiptParacrossDone, isDel bool) (*types.LocalDBSet, error) { status := &pt.ParacrossNodeStatus{ MainBlockHash: commitDone.MainBlockHash, @@ -328,7 +328,7 @@ func (c *Paracross) updateLocalAssetTransfer(tx *types.Transaction, paraHeight i return &types.KeyValue{Key: key, Value: types.Encode(&asset)}, nil } -//IsFriend call exec is same seariase exec +// IsFriend call exec is same seariase exec func (c *Paracross) IsFriend(myexec, writekey []byte, tx *types.Transaction) bool { //不允许平行链 cfg := c.GetAPI().GetConfig() diff --git a/plugin/dapp/paracross/executor/query.go b/plugin/dapp/paracross/executor/query.go index 2efe5248c1..203e9f2667 100644 --- a/plugin/dapp/paracross/executor/query.go +++ b/plugin/dapp/paracross/executor/query.go @@ -72,7 +72,7 @@ func (p *Paracross) Query_GetTitleByHash(in *pt.ReqParacrossTitleHash) (types.Me return p.paracrossGetHeight(in.GetTitle()) } -//Query_GetNodeGroupAddrs get node group addrs +// Query_GetNodeGroupAddrs get node group addrs func (p *Paracross) Query_GetNodeGroupAddrs(in *pt.ReqParacrossNodeInfo) (types.Message, error) { if in == nil { return nil, types.ErrInvalidParam @@ -103,7 +103,7 @@ func (p *Paracross) Query_GetNodeGroupAddrs(in *pt.ReqParacrossNodeInfo) (types. return &reply, nil } -//Query_GetNodeGroupAddrs get node group addrs +// Query_GetNodeGroupAddrs get node group addrs func (p *Paracross) Query_GetSupervisionNodeGroupAddrs(in *pt.ReqParacrossNodeInfo) (types.Message, error) { if in == nil { return nil, types.ErrInvalidParam @@ -134,7 +134,7 @@ func (p *Paracross) Query_GetSupervisionNodeGroupAddrs(in *pt.ReqParacrossNodeIn return &reply, nil } -//Query_GetNodeAddrInfo get specific node addr info +// Query_GetNodeAddrInfo get specific node addr info func (p *Paracross) Query_GetNodeAddrInfo(in *pt.ReqParacrossNodeInfo) (types.Message, error) { if in == nil || in.Addr == "" { return nil, types.ErrInvalidParam @@ -175,7 +175,7 @@ func (p *Paracross) getMainHeight() (int64, error) { return mainHeight, nil } -//Query_GetNodeIDInfo get specific node addr info +// Query_GetNodeIDInfo get specific node addr info func (p *Paracross) Query_GetNodeIDInfo(in *pt.ReqParacrossNodeInfo) (types.Message, error) { if in == nil || in.Id == "" { return nil, types.ErrInvalidParam @@ -203,7 +203,7 @@ func (p *Paracross) Query_GetNodeIDInfo(in *pt.ReqParacrossNodeInfo) (types.Mess return stat, nil } -//Query_ListNodeStatusInfo list node info by status +// Query_ListNodeStatusInfo list node info by status func (p *Paracross) Query_ListNodeStatusInfo(in *pt.ReqParacrossNodeInfo) (types.Message, error) { if in == nil || in.Title == "" { return nil, types.ErrInvalidParam @@ -227,7 +227,7 @@ func (p *Paracross) Query_ListNodeStatusInfo(in *pt.ReqParacrossNodeInfo) (types return resp, nil } -//Query_GetNodeGroupStatus get specific node addr info +// Query_GetNodeGroupStatus get specific node addr info func (p *Paracross) Query_GetNodeGroupStatus(in *pt.ReqParacrossNodeInfo) (types.Message, error) { if in == nil || in.Title == "" { return nil, types.ErrInvalidParam @@ -247,7 +247,7 @@ func (p *Paracross) Query_GetNodeGroupStatus(in *pt.ReqParacrossNodeInfo) (types return stat, nil } -//Query_ListNodeGroupStatus list node info by status +// Query_ListNodeGroupStatus list node info by status func (p *Paracross) Query_ListNodeGroupStatus(in *pt.ReqParacrossNodeInfo) (types.Message, error) { if in == nil { return nil, types.ErrInvalidParam @@ -272,7 +272,7 @@ func (p *Paracross) Query_ListNodeGroupStatus(in *pt.ReqParacrossNodeInfo) (type return resp, nil } -//Query_ListSupervisionNodeStatusInfo list node info by status +// Query_ListSupervisionNodeStatusInfo list node info by status func (p *Paracross) Query_ListSupervisionNodeStatusInfo(in *pt.ReqParacrossNodeInfo) (types.Message, error) { if in == nil || in.Title == "" { return nil, types.ErrInvalidParam @@ -297,7 +297,7 @@ func (p *Paracross) Query_ListSupervisionNodeStatusInfo(in *pt.ReqParacrossNodeI return resp, nil } -//Query_ListTitles query paracross titles list +// Query_ListTitles query paracross titles list func (p *Paracross) Query_ListTitles(in *types.ReqNil) (types.Message, error) { return p.paracrossListTitles() } @@ -442,7 +442,7 @@ func listNodeGroupStatus(db dbm.KVDB, prefix []byte) (types.Message, error) { return &resp, nil } -//按状态遍历 +// 按状态遍历 func listLocalNodeStatus(db dbm.KVDB, title string, status int32) (types.Message, error) { var prefix []byte if status == 0 { @@ -512,7 +512,7 @@ func (p *Paracross) paracrossGetAssetTxResult(hash []byte) (types.Message, error return &rst, nil } -//Query_GetSelfConsStages get self consensus stages configed +// Query_GetSelfConsStages get self consensus stages configed func (p *Paracross) Query_GetSelfConsStages(in *types.ReqNil) (types.Message, error) { stages, err := getSelfConsensStages(p.GetStateDB()) if err != nil { @@ -522,7 +522,7 @@ func (p *Paracross) Query_GetSelfConsStages(in *types.ReqNil) (types.Message, er return stages, nil } -//Query_GetSelfConsOneStage get self consensus one stage +// Query_GetSelfConsOneStage get self consensus one stage func (p *Paracross) Query_GetSelfConsOneStage(in *types.Int64) (types.Message, error) { stage, err := getSelfConsOneStage(p.GetStateDB(), in.Data) if errors.Cause(err) == pt.ErrKeyNotExist { @@ -540,7 +540,7 @@ func (p *Paracross) Query_ListSelfStages(in *pt.ReqQuerySelfStages) (types.Messa return p.listSelfStages(in) } -//Query_GetBlock2MainInfo ... +// Query_GetBlock2MainInfo ... func (p *Paracross) Query_GetBlock2MainInfo(req *types.ReqBlocks) (*pt.ParaBlock2MainInfo, error) { ret := &pt.ParaBlock2MainInfo{} details, err := p.GetAPI().GetBlocks(req) @@ -561,7 +561,7 @@ func (p *Paracross) Query_GetBlock2MainInfo(req *types.ReqBlocks) (*pt.ParaBlock return ret, nil } -//Query_GetHeight ... +// Query_GetHeight ... func (p *Paracross) Query_GetHeight(req *types.ReqString) (*pt.ParacrossConsensusStatus, error) { cfg := p.GetAPI().GetConfig() if req == nil || req.Data == "" { diff --git a/plugin/dapp/paracross/executor/reward.go b/plugin/dapp/paracross/executor/reward.go index aa5f603fad..1402759374 100644 --- a/plugin/dapp/paracross/executor/reward.go +++ b/plugin/dapp/paracross/executor/reward.go @@ -39,7 +39,7 @@ func (a *action) rewardDeposit(rewards []*pt.ParaMinerReward, statusHeight int64 return receipt, nil } -//奖励委托挖矿账户 +// 奖励委托挖矿账户 func (a *action) rewardBindAddr(coinReward int64, nodes []string, bindNodeList map[string][]*pt.ParaBindMinerInfo, statusHeight int64) (*types.Receipt, int64, error) { if coinReward <= 0 || len(bindNodeList) <= 0 { return nil, 0, nil @@ -151,9 +151,7 @@ func (a *action) reward(nodeStatus *pt.ParacrossNodeStatus, stat *pt.ParacrossHe receipt := &types.Receipt{Ty: types.ExecOk} miners := nodeAddrs - for _, addr := range supervisionAddrs { - miners = append(miners, addr) - } + miners = append(miners, supervisionAddrs...) r, change, err := a.rewardSuperNode(superNodeRewards, miners, nodeStatus.Height) if err != nil { return nil, err diff --git a/plugin/dapp/paracross/executor/rollupcrosstx.go b/plugin/dapp/paracross/executor/rollupcrosstx.go index be8dd8d4b5..c5f0801bad 100644 --- a/plugin/dapp/paracross/executor/rollupcrosstx.go +++ b/plugin/dapp/paracross/executor/rollupcrosstx.go @@ -15,13 +15,13 @@ import ( pt "github.com/33cn/plugin/plugin/dapp/paracross/types" ) -//Exec_RollupCrossTx exec commit rollup +// Exec_RollupCrossTx exec commit rollup func (p *Paracross) Exec_RollupCrossTx(commit *pt.RollupCrossTx, tx *types.Transaction, index int) (*types.Receipt, error) { a := newAction(p, tx) return a.rollupCrossTx(commit) } -//当区块回滚时,框架支持自动回滚localdb kv,需要对exec-local返回的kv进行封装 +// 当区块回滚时,框架支持自动回滚localdb kv,需要对exec-local返回的kv进行封装 func (p *Paracross) setAutoRollBack(tx *types.Transaction, kv []*types.KeyValue) *types.LocalDBSet { dbSet := &types.LocalDBSet{} @@ -29,7 +29,7 @@ func (p *Paracross) setAutoRollBack(tx *types.Transaction, kv []*types.KeyValue) return dbSet } -//ExecLocal_RollupCrossTx exec local commit rollup +// ExecLocal_RollupCrossTx exec local commit rollup func (p *Paracross) ExecLocal_RollupCrossTx(commit *pt.RollupCrossTx, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { @@ -67,7 +67,7 @@ func (p *Paracross) ExecLocal_RollupCrossTx(commit *pt.RollupCrossTx, tx *types. return p.setAutoRollBack(tx, dbSet.KV), nil } -//ExecDelLocal_RollupCrossTx exec local commit rollup +// ExecDelLocal_RollupCrossTx exec local commit rollup func (p *Paracross) ExecDelLocal_RollupCrossTx(_ *pt.RollupCrossTx, tx *types.Transaction, _ *types.ReceiptData, _ int) (*types.LocalDBSet, error) { kvs, err := p.DelRollbackKV(tx, tx.Execer) diff --git a/plugin/dapp/paracross/executor/stage.go b/plugin/dapp/paracross/executor/stage.go index 1eb39ec8b9..95b2935643 100644 --- a/plugin/dapp/paracross/executor/stage.go +++ b/plugin/dapp/paracross/executor/stage.go @@ -298,7 +298,7 @@ func (a *action) stageVote(config *pt.ConfigVoteInfo) (*types.Receipt, error) { } -//SelfConsensStageConfig support self consens stage config +// SelfConsensStageConfig support self consens stage config func (a *action) SelfStageConfig(config *pt.ParaStageConfig) (*types.Receipt, error) { if config.Ty == pt.ParaOpNewApply { return a.stageApply(config.GetStage()) diff --git a/plugin/dapp/paracross/executor/stagetable.go b/plugin/dapp/paracross/executor/stagetable.go index 263fc2ec62..e1350f76e2 100644 --- a/plugin/dapp/paracross/executor/stagetable.go +++ b/plugin/dapp/paracross/executor/stagetable.go @@ -22,7 +22,7 @@ var boardOpt = &table.Option{ Index: []string{"id", "status"}, } -//NewStageTable 新建表 +// NewStageTable 新建表 func NewStageTable(kvdb db.KV) *table.Table { rowmeta := NewStageRow() table, err := table.NewTable(rowmeta, kvdb, boardOpt) @@ -32,22 +32,22 @@ func NewStageTable(kvdb db.KV) *table.Table { return table } -//StageRow table meta 结构 +// StageRow table meta 结构 type StageRow struct { *pt.LocalSelfConsStageInfo } -//NewStageRow 新建一个meta 结构 +// NewStageRow 新建一个meta 结构 func NewStageRow() *StageRow { return &StageRow{LocalSelfConsStageInfo: &pt.LocalSelfConsStageInfo{}} } -//CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) +// CreateRow 新建数据行(注意index 数据一定也要保存到数据中,不能就保存heightindex) func (r *StageRow) CreateRow() *table.Row { return &table.Row{Data: &pt.LocalSelfConsStageInfo{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *StageRow) SetPayload(data types.Message) error { if d, ok := data.(*pt.LocalSelfConsStageInfo); ok { r.LocalSelfConsStageInfo = d @@ -56,7 +56,7 @@ func (r *StageRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *StageRow) Get(key string) ([]byte, error) { if key == "heightindex" { return []byte(r.TxIndex), nil diff --git a/plugin/dapp/paracross/executor/superaccount_test.go b/plugin/dapp/paracross/executor/superaccount_test.go index 3c2e3f743e..3c9a491d4e 100644 --- a/plugin/dapp/paracross/executor/superaccount_test.go +++ b/plugin/dapp/paracross/executor/superaccount_test.go @@ -48,7 +48,7 @@ func createRawNodeConfigTx(config *pt.ParaNodeAddrConfig) (*types.Transaction, e return tx, nil } -//createRawNodeGroupApplyTx create raw tx for node group +// createRawNodeGroupApplyTx create raw tx for node group func createRawNodeGroupApplyTx(apply *pt.ParaNodeGroupConfig) (*types.Transaction, error) { apply.Id = strings.Trim(apply.Id, " ") diff --git a/plugin/dapp/paracross/executor/supervisionaccount.go b/plugin/dapp/paracross/executor/supervisionaccount.go index cc430fbab3..ae06dbfb1c 100644 --- a/plugin/dapp/paracross/executor/supervisionaccount.go +++ b/plugin/dapp/paracross/executor/supervisionaccount.go @@ -173,7 +173,7 @@ func (a *action) supervisionNodeGroupCreate(title, targetAddrs string) (*types.R return receipt, nil } -//由于propasal id 和quit id分开,quit id不知道对应addr proposal id的coinfrozen信息,需要维护一个围绕addr的数据库结构信息 +// 由于propasal id 和quit id分开,quit id不知道对应addr proposal id的coinfrozen信息,需要维护一个围绕addr的数据库结构信息 func (a *action) updateSupervisionNodeAddrStatus(stat *pt.ParaNodeGroupStatus) (*types.Receipt, error) { addrStat, err := getNodeAddr(a.db, stat.Title, stat.TargetAddrs) if err != nil { diff --git a/plugin/dapp/paracross/testnode/cfg.go b/plugin/dapp/paracross/testnode/cfg.go index 924191b43f..8645309f6c 100644 --- a/plugin/dapp/paracross/testnode/cfg.go +++ b/plugin/dapp/paracross/testnode/cfg.go @@ -1,6 +1,6 @@ package testnode -//DefaultConfig default config for testnode +// DefaultConfig default config for testnode var DefaultConfig = ` Title="user.p.test." CoinSymbol="bty" diff --git a/plugin/dapp/paracross/testnode/paranode.go b/plugin/dapp/paracross/testnode/paranode.go index 8186f60e96..3424ff0df3 100644 --- a/plugin/dapp/paracross/testnode/paranode.go +++ b/plugin/dapp/paracross/testnode/paranode.go @@ -11,13 +11,13 @@ import ( 2. 启动一个平行链节点:注意,这个要测试的话,会依赖平行链插件 */ -//ParaNode 平行链节点由两个节点组成 +// ParaNode 平行链节点由两个节点组成 type ParaNode struct { Main *testnode.Chain33Mock Para *testnode.Chain33Mock } -//NewParaNode 创建一个平行链节点 +// NewParaNode 创建一个平行链节点 func NewParaNode(main *testnode.Chain33Mock, para *testnode.Chain33Mock) *ParaNode { if main == nil { main = testnode.New("", nil) @@ -35,7 +35,7 @@ func NewParaNode(main *testnode.Chain33Mock, para *testnode.Chain33Mock) *ParaNo return &ParaNode{Main: main, Para: para} } -//Close 关闭系统 +// Close 关闭系统 func (node *ParaNode) Close() { node.Para.Close() node.Main.Close() diff --git a/plugin/dapp/paracross/types/parabls.pb.go b/plugin/dapp/paracross/types/parabls.pb.go index 84d50ce83b..7faf79402e 100644 --- a/plugin/dapp/paracross/types/parabls.pb.go +++ b/plugin/dapp/paracross/types/parabls.pb.go @@ -370,7 +370,7 @@ func (*ParaP2PSubMsg_CommitTx) isParaP2PSubMsg_Value() {} func (*ParaP2PSubMsg_SyncMsg) isParaP2PSubMsg_Value() {} -//bls sign leader info +// bls sign leader info type ElectionStatus struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/paracross/types/paracross.go b/plugin/dapp/paracross/types/paracross.go index af75337af0..519ab04a39 100644 --- a/plugin/dapp/paracross/types/paracross.go +++ b/plugin/dapp/paracross/types/paracross.go @@ -89,9 +89,9 @@ const ( //paraCrossTransferActionTypeEnd = 10100 ) -//跨链转移类型是特别执行跨链资产转移的处理,在共识通过后,会做相应处理,其他类型都认为是普通paracross类型 -//跨链资产转移的类型都放到paraCrossTransferActionTypeStart之后,方便管理 -//这里NodeConfig,NodeGroupApply和SelfStageConfig虽然都是跨链类型,但是不算跨链资产转移,实际上不应该放这一类,历史版本就不修改了。 +// 跨链转移类型是特别执行跨链资产转移的处理,在共识通过后,会做相应处理,其他类型都认为是普通paracross类型 +// 跨链资产转移的类型都放到paraCrossTransferActionTypeStart之后,方便管理 +// 这里NodeConfig,NodeGroupApply和SelfStageConfig虽然都是跨链类型,但是不算跨链资产转移,实际上不应该放这一类,历史版本就不修改了。 const ( // ParacrossActionAssetTransfer mainchain paracross asset transfer key ParacrossActionAssetTransfer = iota + paraCrossTransferActionTypeStart @@ -110,7 +110,7 @@ const ( ParacrossActionCrossAssetTransfer ) -//跨链共识交易crossResult bitmap版本,支持多版本的bitmap管理 +// 跨链共识交易crossResult bitmap版本,支持多版本的bitmap管理 const ( ParaCrossStatusBitMapVerLen = 4 ParaCrossStatusBitMapVer1 = "0001" @@ -118,13 +118,13 @@ const ( const ParaPrefix = "user.p." -//配置跨链交易高度列表的prefix 比如hit.para.100.200,ignore.para.100-300 +// 配置跨链交易高度列表的prefix 比如hit.para.100.200,ignore.para.100-300 const ( ParaCrossAssetTxHitKey = "hit" ParaCrossAssetTxIgnoreKey = "ignore" ) -//paracross asset porcess +// paracross asset porcess const ( ParacrossNoneTransfer = iota ParacrossMainAssetTransfer @@ -158,7 +158,7 @@ const ( ParaVoteEnd ) -//config yes or no +// config yes or no const ( ParaConfigInvalid = iota ParaConfigYes @@ -168,7 +168,7 @@ const ( // ParaNodeVoteStr ... var ParaNodeVoteStr = []string{"invalid", "yes", "no"} -//针对addr申请的id的生命周期 +// 针对addr申请的id的生命周期 const ( // ParaApplyJoining apply for join group ParaApplyJoining = iota + 1 @@ -182,7 +182,7 @@ const ( ParaApplyVoting ) -//针对addr本身的生命周期,addr维护了申请id和quit id,方便查询如coinfrozen等额外信息 +// 针对addr本身的生命周期,addr维护了申请id和quit id,方便查询如coinfrozen等额外信息 const ( // ParaApplyJoined pass to add by votes ParaApplyJoined = iota + 10 @@ -354,7 +354,7 @@ func (p ParacrossType) CreateRawTransferTx(action string, param json.RawMessage) return tx, nil } -//GetDappForkHeight get paracross dapp fork height +// GetDappForkHeight get paracross dapp fork height func GetDappForkHeight(cfg *types.Chain33Config, forkKey string) int64 { var forkHeight int64 if cfg.IsPara() { diff --git a/plugin/dapp/paracross/types/paracross.pb.go b/plugin/dapp/paracross/types/paracross.pb.go index 78a6b318ee..8b6a289af7 100644 --- a/plugin/dapp/paracross/types/paracross.pb.go +++ b/plugin/dapp/paracross/types/paracross.pb.go @@ -82,7 +82,7 @@ func (x *ParacrossStatusDetails) GetBlockHash() [][]byte { return nil } -//记录不同blockHash的详细数据 +// 记录不同blockHash的详细数据 type ParacrossStatusBlockDetails struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1120,7 +1120,7 @@ func (x *ConfigCancelInfo) GetId() string { return "" } -//广义配置类型 +// 广义配置类型 type ParaStageConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/paracross/types/paraminer.pb.go b/plugin/dapp/paracross/types/paraminer.pb.go index 9c27f862dd..5895191822 100644 --- a/plugin/dapp/paracross/types/paraminer.pb.go +++ b/plugin/dapp/paracross/types/paraminer.pb.go @@ -22,7 +22,7 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -//para bind miner +// para bind miner type ParaBindMinerCmd struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -244,7 +244,7 @@ func (x *ReceiptParaBindMinerInfo) GetCurrent() *ParaBindMinerInfo { return nil } -//共识节点绑定全局状态 +// 共识节点绑定全局状态 type ParaBindNodeInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -355,7 +355,7 @@ func (x *ReceiptParaBindConsensusNodeInfo) GetCurrent() *ParaBindNodeInfo { return nil } -//共识节点索引绑定挖矿地址 +// 共识节点索引绑定挖矿地址 type ParaBindAddr struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/paracross/types/type.go b/plugin/dapp/paracross/types/type.go index fc818caeeb..1dc7690a60 100644 --- a/plugin/dapp/paracross/types/type.go +++ b/plugin/dapp/paracross/types/type.go @@ -65,7 +65,7 @@ func init() { } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(ParaX, "Enable", 0) cfg.RegisterDappFork(ParaX, "ForkParacrossWithdrawFromParachain", 0) @@ -83,7 +83,7 @@ func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(ParaX, ForkParaRootHash, types.MaxHeight) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(ParaX, NewType(cfg)) } diff --git a/plugin/dapp/paracross/wallet/para.go b/plugin/dapp/paracross/wallet/para.go index 9fd250bc18..d5432e2fac 100644 --- a/plugin/dapp/paracross/wallet/para.go +++ b/plugin/dapp/paracross/wallet/para.go @@ -69,7 +69,7 @@ func (policy *ParaPolicy) OnWalletLocked() { bizlog.Info("OnWalletLocked", "IsWalletLock", walletsatus.IsWalletLock) } -//解锁超时处理,需要区分整个钱包的解锁或者只挖矿的解锁 +// 解锁超时处理,需要区分整个钱包的解锁或者只挖矿的解锁 func (policy *ParaPolicy) resetTimeout(Timeout int64) { if policy.minertimeout == nil { policy.minertimeout = time.AfterFunc(time.Second*time.Duration(Timeout), func() { diff --git a/plugin/dapp/pokerbull/executor/pokerbull.go b/plugin/dapp/pokerbull/executor/pokerbull.go index dc13ee88a5..70a355c148 100644 --- a/plugin/dapp/pokerbull/executor/pokerbull.go +++ b/plugin/dapp/pokerbull/executor/pokerbull.go @@ -25,7 +25,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { var driverName = pkt.PokerBullX -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&PokerBull{})) diff --git a/plugin/dapp/pokerbull/executor/pokerbulldb.go b/plugin/dapp/pokerbull/executor/pokerbulldb.go index 63d6d9d303..d5c7ec3ac6 100644 --- a/plugin/dapp/pokerbull/executor/pokerbulldb.go +++ b/plugin/dapp/pokerbull/executor/pokerbulldb.go @@ -598,7 +598,7 @@ func (action *Action) GameStart(start *pkt.PBGameStart) (*types.Receipt, error) // 参数校验 if start.PlayerNum <= 0 || start.Value < 0 { logger.Error("GameStart", "addr", action.fromaddr, "execaddr", action.execaddr, - "err", fmt.Sprintf("Invalid parameter")) + "err", "Invalid parameter") return nil, types.ErrInvalidParam } @@ -897,7 +897,7 @@ func (action *Action) GamePlay(pbplay *pkt.PBGamePlay) (*types.Receipt, error) { // 参数校验 if pbplay.Round <= 0 || pbplay.Value <= 0 { logger.Error("GameStart", "addr", action.fromaddr, "execaddr", action.execaddr, - "err", fmt.Sprintf("Invalid parameter")) + "err", "Invalid parameter") return nil, types.ErrInvalidParam } diff --git a/plugin/dapp/pokerbull/types/const.go b/plugin/dapp/pokerbull/types/const.go index 84b101328d..b25ba83673 100644 --- a/plugin/dapp/pokerbull/types/const.go +++ b/plugin/dapp/pokerbull/types/const.go @@ -4,7 +4,7 @@ package types -//game action ty +// game action ty const ( PBGameActionStart = iota + 1 PBGameActionContinue @@ -33,9 +33,9 @@ const ( TyLogPBGamePlay = 725 ) -//包的名字可以通过配置文件来配置 -//建议用github的组织名称,或者用户名字开头, 再加上自己的插件的名字 -//如果发生重名,可以通过配置文件修改这些名字 +// 包的名字可以通过配置文件来配置 +// 建议用github的组织名称,或者用户名字开头, 再加上自己的插件的名字 +// 如果发生重名,可以通过配置文件修改这些名字 var ( JRPCName = "pokerbull" PokerBullX = "pokerbull" diff --git a/plugin/dapp/pokerbull/types/pokerbull.pb.go b/plugin/dapp/pokerbull/types/pokerbull.pb.go index 50577bedbb..d23572151f 100644 --- a/plugin/dapp/pokerbull/types/pokerbull.pb.go +++ b/plugin/dapp/pokerbull/types/pokerbull.pb.go @@ -21,7 +21,7 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -//斗牛游戏内容 +// 斗牛游戏内容 type PokerBull struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -197,7 +197,7 @@ func (x *PokerBull) GetRound() int32 { return 0 } -//一把牌 +// 一把牌 type PBHand struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -277,7 +277,7 @@ func (x *PBHand) GetLeverage() int32 { return 0 } -//玩家 +// 玩家 type PBPlayer struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -349,7 +349,7 @@ func (x *PBPlayer) GetReady() bool { return false } -//本局游戏结果 +// 本局游戏结果 type PBResult struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -429,7 +429,7 @@ func (x *PBResult) GetDealerLeverage() int32 { return 0 } -//扑克牌 +// 扑克牌 type PBPoker struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -485,7 +485,7 @@ func (x *PBPoker) GetPointer() int32 { return 0 } -//游戏状态 +// 游戏状态 type PBGameAction struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -616,7 +616,7 @@ func (*PBGameAction_Query) isPBGameAction_Value() {} func (*PBGameAction_Play) isPBGameAction_Value() {} -//游戏启动 +// 游戏启动 type PBGameStart struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -672,7 +672,7 @@ func (x *PBGameStart) GetPlayerNum() int32 { return 0 } -//游戏继续 +// 游戏继续 type PBGameContinue struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -720,7 +720,7 @@ func (x *PBGameContinue) GetGameId() string { return "" } -//游戏结束 +// 游戏结束 type PBGameQuit struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -768,7 +768,7 @@ func (x *PBGameQuit) GetGameId() string { return "" } -//查询游戏结果 +// 查询游戏结果 type PBGameQuery struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -816,7 +816,7 @@ func (x *PBGameQuery) GetGameId() string { return "" } -//已匹配玩家直接游戏 +// 已匹配玩家直接游戏 type PBGamePlay struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -888,7 +888,7 @@ func (x *PBGamePlay) GetAddress() []string { return nil } -//根据状态和游戏人数查找 +// 根据状态和游戏人数查找 type QueryPBGameListByStatusAndPlayerNum struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/pokerbull/types/types.go b/plugin/dapp/pokerbull/types/types.go index 4fcaae7cb2..8e8f257a4a 100644 --- a/plugin/dapp/pokerbull/types/types.go +++ b/plugin/dapp/pokerbull/types/types.go @@ -17,12 +17,12 @@ func init() { types.RegExec(PokerBullX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(PokerBullX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(PokerBullX, NewType(cfg)) } diff --git a/plugin/dapp/privacy/autotest/createutxosCase.go b/plugin/dapp/privacy/autotest/createutxosCase.go index f2bc52174e..bacfe4aed4 100644 --- a/plugin/dapp/privacy/autotest/createutxosCase.go +++ b/plugin/dapp/privacy/autotest/createutxosCase.go @@ -10,8 +10,8 @@ import ( "github.com/33cn/chain33/cmd/autotest/types" ) -//CreateUtxosCase pub2priv case -//Deprecated:已经删除CreateUtxo功能, 用pub2priv替代 +// CreateUtxosCase pub2priv case +// Deprecated:已经删除CreateUtxo功能, 用pub2priv替代 type CreateUtxosCase struct { types.BaseCase From string `toml:"from"` diff --git a/plugin/dapp/privacy/autotest/privToPrivCase.go b/plugin/dapp/privacy/autotest/privToPrivCase.go index e068826698..d992a92d6f 100644 --- a/plugin/dapp/privacy/autotest/privToPrivCase.go +++ b/plugin/dapp/privacy/autotest/privToPrivCase.go @@ -10,7 +10,7 @@ import ( "github.com/33cn/chain33/cmd/autotest/types" ) -//PrivToPrivCase pub2priv case +// PrivToPrivCase pub2priv case type PrivToPrivCase struct { types.BaseCase From string `toml:"from"` diff --git a/plugin/dapp/privacy/autotest/privToPubCase.go b/plugin/dapp/privacy/autotest/privToPubCase.go index 83c7cec0f9..e58a6c2f19 100644 --- a/plugin/dapp/privacy/autotest/privToPubCase.go +++ b/plugin/dapp/privacy/autotest/privToPubCase.go @@ -10,7 +10,7 @@ import ( "github.com/33cn/chain33/cmd/autotest/types" ) -//PrivToPubCase pub2priv case +// PrivToPubCase pub2priv case type PrivToPubCase struct { types.BaseCase From string `toml:"from"` diff --git a/plugin/dapp/privacy/autotest/pubToPriv.go b/plugin/dapp/privacy/autotest/pubToPriv.go index bf43738b95..27a860df0d 100644 --- a/plugin/dapp/privacy/autotest/pubToPriv.go +++ b/plugin/dapp/privacy/autotest/pubToPriv.go @@ -10,7 +10,7 @@ import ( "github.com/33cn/chain33/cmd/autotest/types" ) -//PubToPrivCase pub2priv case +// PubToPrivCase pub2priv case type PubToPrivCase struct { types.BaseCase From string `toml:"from"` diff --git a/plugin/dapp/privacy/commands/privacy.go b/plugin/dapp/privacy/commands/privacy.go index b167703bee..6102883187 100644 --- a/plugin/dapp/privacy/commands/privacy.go +++ b/plugin/dapp/privacy/commands/privacy.go @@ -382,7 +382,7 @@ func parseShowPrivacyAccountSpendRes(arg ...interface{}) (interface{}, error) { } } - fmt.Println(fmt.Sprintf("Total Privacy spend amount is %s", types.FormatAmount2FloatDisplay(total, cfg.CoinPrecision, true))) + fmt.Printf("Total Privacy spend amount is %s\n", types.FormatAmount2FloatDisplay(total, cfg.CoinPrecision, true)) return rets, nil } diff --git a/plugin/dapp/privacy/crypto/privacy.go b/plugin/dapp/privacy/crypto/privacy.go index fb9d26f8d2..e3a9144cbf 100644 --- a/plugin/dapp/privacy/crypto/privacy.go +++ b/plugin/dapp/privacy/crypto/privacy.go @@ -41,7 +41,6 @@ type sigcomm struct { comm ellipticCurvePoint } -// type sigcommArray [32 * 3]byte // KeyImage key image type @@ -88,8 +87,8 @@ func NewPrivacyWithPrivKey(privKey *[KeyLen32]byte) (privacy *Privacy, err error return privacy, nil } -//GenerateOneTimeAddr (A, B) => Hs(rA)G + B, rG=>R -//func GenerateOneTimeAddr(viewPub, spendPub, skAddr32 *[32]byte, outputIndex int64) (pubkeyOnetime, RtxPublicKey *[32]byte, errInfo error) { +// GenerateOneTimeAddr (A, B) => Hs(rA)G + B, rG=>R +// func GenerateOneTimeAddr(viewPub, spendPub, skAddr32 *[32]byte, outputIndex int64) (pubkeyOnetime, RtxPublicKey *[32]byte, errInfo error) { func GenerateOneTimeAddr(viewPub, spendPub, skAddr32 *[32]byte, outputIndex int64) (pubkeyOnetime *[32]byte, errInfo error) { //to calculate rA @@ -138,7 +137,7 @@ func GenerateOneTimeAddr(viewPub, spendPub, skAddr32 *[32]byte, outputIndex int6 return } -//RecoverOnetimePriKey calculate Hs(aR) + b +// RecoverOnetimePriKey calculate Hs(aR) + b func RecoverOnetimePriKey(R []byte, viewSecretKey, spendSecretKey crypto.PrivKey, outputIndex int64) (crypto.PrivKey, error) { var viewSecAddr, spendSecAddr, RtxPubAddr *[32]byte viewSecAddr = (*[32]byte)(unsafe.Pointer(&viewSecretKey.Bytes()[0])) diff --git a/plugin/dapp/privacy/executor/kv.go b/plugin/dapp/privacy/executor/kv.go index 018d42d79b..45d8aabcd8 100644 --- a/plugin/dapp/privacy/executor/kv.go +++ b/plugin/dapp/privacy/executor/kv.go @@ -21,7 +21,7 @@ const ( invalidIndex = -1 ) -//计算隐私资产utxo的前缀, 和exec,token相关 +// 计算隐私资产utxo的前缀, 和exec,token相关 func calcUtxoAssetPrefix(exec, token string) string { //只有coins资产的key不加exec前缀, 主要考虑是不加分叉兼容历史隐私交易 if exec == "" || exec == types.DefaultCoinsExec { @@ -30,8 +30,8 @@ func calcUtxoAssetPrefix(exec, token string) string { return exec + ":" + token } -//CalcPrivacyOutputKey 该key对应的是types.KeyOutput -//该kv会在store中设置 +// CalcPrivacyOutputKey 该key对应的是types.KeyOutput +// 该kv会在store中设置 func CalcPrivacyOutputKey(exec, token string, amount int64, txhash string, outindex int) (key []byte) { return []byte(fmt.Sprintf(privacyOutputKeyPrefix+"-%s-%d-%s-%d", calcUtxoAssetPrefix(exec, token), amount, txhash, outindex)) } @@ -40,7 +40,7 @@ func calcPrivacyKeyImageKey(exec, token string, keyimage []byte) []byte { return []byte(fmt.Sprintf(privacyKeyImagePrefix+"-%s-%s", calcUtxoAssetPrefix(exec, token), common.ToHex(keyimage))) } -//CalcPrivacyUTXOkeyHeight 在本地数据库中设置一条可以找到对应amount的对应的utxo的global index +// CalcPrivacyUTXOkeyHeight 在本地数据库中设置一条可以找到对应amount的对应的utxo的global index func CalcPrivacyUTXOkeyHeight(exec, token string, amount, height int64, txhash string, txindex, outindex int) (key []byte) { return []byte(fmt.Sprintf(privacyUTXOKEYPrefix+"-%s-%s-%d-%d-%s-%d-%d", exec, token, amount, height, txhash, txindex, outindex)) } @@ -50,7 +50,7 @@ func CalcPrivacyUTXOkeyHeightPrefix(exec, token string, amount int64) (key []byt return []byte(fmt.Sprintf(privacyUTXOKEYPrefix+"-%s-%s-%d-", exec, token, amount)) } -//CalcprivacyKeyTokenAmountType 设置当前系统存在的token的amount的类型,如存在1,3,5,100...等等的类型, +// CalcprivacyKeyTokenAmountType 设置当前系统存在的token的amount的类型,如存在1,3,5,100...等等的类型, func CalcprivacyKeyTokenAmountType(exec, token string) (key []byte) { return []byte(fmt.Sprintf(privacyAmountTypePrefix+"-%s-%s-", exec, token)) } diff --git a/plugin/dapp/privacy/executor/privacy.go b/plugin/dapp/privacy/executor/privacy.go index e97cae92d7..53f21b332a 100644 --- a/plugin/dapp/privacy/executor/privacy.go +++ b/plugin/dapp/privacy/executor/privacy.go @@ -46,7 +46,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&privacy{})) @@ -148,9 +148,9 @@ func (p *privacy) getGlobalUtxoIndex(req *pty.ReqUTXOGlobalIndex) (types.Message return utxoGlobalIndexResp, nil } -//ShowAmountsOfUTXO 获取指定amount下的所有utxo,这样就可以查询当前系统不同amout下存在的UTXO,可以帮助查询用于混淆用的资源 -//也可以确认币种的碎片化问题 -//显示存在的各种不同的额度的UTXO,如1,3,5,10,20,30,100... +// ShowAmountsOfUTXO 获取指定amount下的所有utxo,这样就可以查询当前系统不同amout下存在的UTXO,可以帮助查询用于混淆用的资源 +// 也可以确认币种的碎片化问题 +// 显示存在的各种不同的额度的UTXO,如1,3,5,10,20,30,100... func (p *privacy) ShowAmountsOfUTXO(reqtoken *pty.ReqPrivacyToken) (types.Message, error) { querydb := p.GetLocalDB() @@ -177,7 +177,7 @@ func (p *privacy) ShowAmountsOfUTXO(reqtoken *pty.ReqPrivacyToken) (types.Messag return replyAmounts, nil } -//ShowUTXOs4SpecifiedAmount 显示在指定额度下的UTXO的具体信息,如区块高度,交易hash,输出索引等具体信息 +// ShowUTXOs4SpecifiedAmount 显示在指定额度下的UTXO的具体信息,如区块高度,交易hash,输出索引等具体信息 func (p *privacy) ShowUTXOs4SpecifiedAmount(reqtoken *pty.ReqPrivacyToken) (types.Message, error) { querydb := p.GetLocalDB() @@ -308,7 +308,7 @@ func batchGet(stateDB db.KV, keyImages [][]byte) (values [][]byte, err error) { return values, nil } -//通过keyImage确认是否存在双花,有效即不存在双花,返回true,反之则返回false +// 通过keyImage确认是否存在双花,有效即不存在双花,返回true,反之则返回false func (p *privacy) checkUTXOValid(keyImages [][]byte) (bool, int32) { stateDB := p.GetStateDB() values, err := batchGet(stateDB, keyImages) diff --git a/plugin/dapp/privacy/types/const.go b/plugin/dapp/privacy/types/const.go index 6d7b8bbcf6..7559f8a952 100644 --- a/plugin/dapp/privacy/types/const.go +++ b/plugin/dapp/privacy/types/const.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//Package types ... +// Package types ... package types const ( @@ -43,7 +43,7 @@ const ( PrivacyTxFee = 1 ) -//const ... +// const ... const ( // utxo缓存数量 UTXOCacheCount = 256 diff --git a/plugin/dapp/privacy/types/privacy.go b/plugin/dapp/privacy/types/privacy.go index c0fdc38f82..9696090d49 100644 --- a/plugin/dapp/privacy/types/privacy.go +++ b/plugin/dapp/privacy/types/privacy.go @@ -45,12 +45,12 @@ func init() { types.RegExec(PrivacyX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(PrivacyX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(PrivacyX, NewType(cfg)) } diff --git a/plugin/dapp/privacy/types/privacy.pb.go b/plugin/dapp/privacy/types/privacy.pb.go index ef79c2f4c7..8a3ff8f1d9 100644 --- a/plugin/dapp/privacy/types/privacy.pb.go +++ b/plugin/dapp/privacy/types/privacy.pb.go @@ -26,10 +26,10 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -////////////////////////////////////////////////////////////////////////////// +// //////////////////////////////////////////////////////////////////////////// // message for Privacy // start///////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// +// //////////////////////////////////////////////////////////////////////////// type PrivacyAction struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1287,7 +1287,7 @@ func (x *ReceiptPrivacyOutput) GetKeyoutput() []*KeyOutput { return nil } -//各种amount额度的UTXO在链上的数量 +// 各种amount额度的UTXO在链上的数量 type AmountsOfUTXO struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/privacy/wallet/keys.go b/plugin/dapp/privacy/wallet/keys.go index 7ff656b0cc..21cbd94564 100644 --- a/plugin/dapp/privacy/wallet/keys.go +++ b/plugin/dapp/privacy/wallet/keys.go @@ -71,13 +71,13 @@ func calcPrivacyDBVersion() []byte { } // calcUTXOKey 计算可用UTXO的健值,为输出交易哈希+输出索引位置 -//key and prefix for privacy -//types.PrivacyDBStore的数据存储由calcUTXOKey生成key, -//1.当该utxo的目的地址是钱包管理的其中一个隐私地址时,该key作为value,保存在calcUTXOKey4TokenAddr由生成的key对应的kv中; -//2.当进行支付时,calcUTXOKey4TokenAddr对应的kv被删除,进而由calcPrivacyFUTXOKey生成的key对应kv中,其中平移的只是key, +// key and prefix for privacy +// types.PrivacyDBStore的数据存储由calcUTXOKey生成key, +// 1.当该utxo的目的地址是钱包管理的其中一个隐私地址时,该key作为value,保存在calcUTXOKey4TokenAddr由生成的key对应的kv中; +// 2.当进行支付时,calcUTXOKey4TokenAddr对应的kv被删除,进而由calcPrivacyFUTXOKey生成的key对应kv中,其中平移的只是key, // 本身的具体数据并不进行重新存储,即将utxo变化为futxo; -//3.当包含该交易的块得到确认时,如果发现输入包含在futxo中,则通过类似的方法,将其key设置到stxo中, -//4.当发生区块链分叉回退时,即发生del block的情况时,同时 +// 3.当包含该交易的块得到确认时,如果发现输入包含在futxo中,则通过类似的方法,将其key设置到stxo中, +// 4.当发生区块链分叉回退时,即发生del block的情况时,同时 // 4.a 当确认其中的输入存在于stxo时,则将其从stxo中转移至ftxo中, // 4.b 当确认其中的输出存在于utxo或ftxo中时,则将其从utxo或ftxo中同时进行删除,同时删除types.PrivacyDBStore在数据库中的值 // 4.c 当确认其中的输出存在于stxo中时,则发生了异常,正常情况下,花费该笔utxo的交易需要被先回退,进而回退该笔交易,观察此种情况的发生 @@ -94,7 +94,7 @@ func calcPrivacyAddrKey(addr string) []byte { return []byte(fmt.Sprintf("%s-%s", Privacy4Addr, address.FormatAddrKey(addr))) } -//calcAddrKey 通过addr地址查询Account账户信息 +// calcAddrKey 通过addr地址查询Account账户信息 func calcAddrKey(addr string) []byte { return []byte(fmt.Sprintf("Addr:%s", address.FormatAddrKey(addr))) } @@ -159,8 +159,8 @@ func calcRevertSendTxKey(assetExec, tokenname, addr, txhash string) []byte { return []byte(fmt.Sprintf("%s:%s-%s-%s-%s", RevertSendtx, assetExec, tokenname, address.FormatAddrKey(addr), txhash)) } -//通过height*100000+index 查询Tx交易信息 -//key:Tx:height*100000+index +// 通过height*100000+index 查询Tx交易信息 +// key:Tx:height*100000+index func calcTxKey(key string) []byte { return []byte(fmt.Sprintf("%s:%s", PrivacyTX, key)) } diff --git a/plugin/dapp/privacy/wallet/privacy.go b/plugin/dapp/privacy/wallet/privacy.go index 8837160a6c..07041099cf 100644 --- a/plugin/dapp/privacy/wallet/privacy.go +++ b/plugin/dapp/privacy/wallet/privacy.go @@ -42,13 +42,13 @@ func (policy *privacyPolicy) rescanAllTxAddToUpdateUTXOs() { bizlog.Debug("rescanAllTxToUpdateUTXOs success!") } -//从blockchain模块同步addr参与的所有交易详细信息 +// 从blockchain模块同步addr参与的所有交易详细信息 func (policy *privacyPolicy) rescanReqTxDetailByAddr(addr string, wg *sync.WaitGroup) { defer wg.Done() policy.reqTxDetailByAddr(addr) } -//从blockchain模块同步addr参与的所有交易详细信息 +// 从blockchain模块同步addr参与的所有交易详细信息 func (policy *privacyPolicy) reqTxDetailByAddr(addr string) { if len(addr) == 0 { bizlog.Error("reqTxDetailByAddr input addr is nil!") @@ -357,6 +357,7 @@ func (policy *privacyPolicy) selectUTXO(assetExec, token, addr string, amount in /* buildInput 构建隐私交易的输入信息 操作步骤 + 1.从当前钱包中选择可用并且足够支付金额的UTXO列表 2.如果需要混淆(mixcout>0),则根据UTXO的金额从数据库中获取足够数量的UTXO,与当前UTXO进行混淆 3.通过公式 x=Hs(aR)+b,计算出一个整数,因为 xG = Hs(ar)G+bG = Hs(aR)G+B,所以可以继续使用这笔交易 @@ -796,7 +797,7 @@ func (policy *privacyPolicy) rescanUTXOs(req *privacytypes.ReqRescanUtxos) (*pri return &repRescanUtxos, nil } -//从blockchain模块同步addr参与的所有交易详细信息 +// 从blockchain模块同步addr参与的所有交易详细信息 func (policy *privacyPolicy) rescanReqUtxosByAddr(addrs []string) { defer policy.getWalletOperate().GetWaitGroup().Done() bizlog.Debug("RescanAllUTXO begin!") @@ -888,7 +889,7 @@ func (policy *privacyPolicy) reqUtxosByAddr(addrs []string) { policy.store.saveREscanUTXOsAddresses(storeAddrs, privacytypes.UtxoFlagScanEnd) } -//TODO:input也可能时混淆的utxo, 需要增加判定实际的utxo +// TODO:input也可能时混淆的utxo, 需要增加判定实际的utxo func (policy *privacyPolicy) deleteScanPrivacyInputUtxo() { maxUTXOsPerTime := 1000 for { diff --git a/plugin/dapp/privacy/wallet/privacystore.go b/plugin/dapp/privacy/wallet/privacystore.go index 5e9c9b172f..f42949bf05 100644 --- a/plugin/dapp/privacy/wallet/privacystore.go +++ b/plugin/dapp/privacy/wallet/privacystore.go @@ -301,10 +301,10 @@ func (store *privacyStore) getPrivacyTokenUTXOs(assetExec, token, addr string) ( return wutxos, nil } -//calcUTXOKey4TokenAddr---X--->calcUTXOKey 被删除,该地址下某种token的这个utxo变为不可用 -//calcKey4UTXOsSpentInTx------>types.FTXOsSTXOsInOneTx,将当前交易的所有花费的utxo进行打包,设置为ftxo,同时通过支付交易hash索引 -//calcKey4FTXOsInTx----------->calcKey4UTXOsSpentInTx,创建该交易冻结的所有的utxo的信息 -//状态转移,将utxo转移至ftxo,同时记录该生成tx的花费的utxo,这样在确认执行成功之后就可以快速将相应的FTXO转换成STXO +// calcUTXOKey4TokenAddr---X--->calcUTXOKey 被删除,该地址下某种token的这个utxo变为不可用 +// calcKey4UTXOsSpentInTx------>types.FTXOsSTXOsInOneTx,将当前交易的所有花费的utxo进行打包,设置为ftxo,同时通过支付交易hash索引 +// calcKey4FTXOsInTx----------->calcKey4UTXOsSpentInTx,创建该交易冻结的所有的utxo的信息 +// 状态转移,将utxo转移至ftxo,同时记录该生成tx的花费的utxo,这样在确认执行成功之后就可以快速将相应的FTXO转换成STXO func (store *privacyStore) moveUTXO2FTXO(expire int64, assetExec, token, sender, txhash string, selectedUtxos []*txOutputInfo) { FTXOsInOneTx := &privacytypes.FTXOsSTXOsInOneTx{ AssetExec: assetExec, @@ -643,9 +643,9 @@ func (store *privacyStore) selectCurrentWalletPrivacyTx(txDetal *types.Transacti // txhash 该UTXO的来源交易输出的交易哈希,没有0x // outindex 该UTXO的来源交易输出的索引位置 // dbStore 构建的钱包UTXO详细数据信息 -//UTXO---->moveUTXO2FTXO---->FTXO---->moveFTXO2STXO---->STXO -//1.calcUTXOKey------------>types.PrivacyDBStore 该kv值在db中的存储一旦写入就不再改变,除非产生该UTXO的交易被撤销 -//2.calcUTXOKey4TokenAddr-->calcUTXOKey,创建kv,方便查询现在某个地址下某种token的可用utxo +// UTXO---->moveUTXO2FTXO---->FTXO---->moveFTXO2STXO---->STXO +// 1.calcUTXOKey------------>types.PrivacyDBStore 该kv值在db中的存储一旦写入就不再改变,除非产生该UTXO的交易被撤销 +// 2.calcUTXOKey4TokenAddr-->calcUTXOKey,创建kv,方便查询现在某个地址下某种token的可用utxo func (store *privacyStore) setUTXO(utxoInfo *privacytypes.PrivacyDBStore, txHash string, newbatch db.Batch) error { privacyStorebyte := types.Encode(utxoInfo) @@ -766,9 +766,9 @@ func (store *privacyStore) getFTXOlist() ([]*privacytypes.FTXOsSTXOsInOneTx, [][ return curFTXOTxs, keys } -//calcKey4FTXOsInTx-----x------>calcKey4UTXOsSpentInTx,被删除, -//calcKey4STXOsInTx------------>calcKey4UTXOsSpentInTx -//切换types.FTXOsSTXOsInOneTx的状态 +// calcKey4FTXOsInTx-----x------>calcKey4UTXOsSpentInTx,被删除, +// calcKey4STXOsInTx------------>calcKey4UTXOsSpentInTx +// 切换types.FTXOsSTXOsInOneTx的状态 func (store *privacyStore) moveFTXO2STXO(key1 []byte, txhash string, newbatch db.Batch) error { //设置在该交易中花费的UTXO value1, err := store.Get(key1) @@ -806,7 +806,7 @@ func (store *privacyStore) moveFTXO2STXO(key1 []byte, txhash string, newbatch db return nil } -//将FTXO重置为UTXO +// 将FTXO重置为UTXO // moveFTXO2UTXO 当交易因为区块被回退而进行回滚时,需要将交易对应的冻结UTXO移动到可用UTXO队列中 // 由于交易回退可能会因为UTXO对应的交易过期,未被打入区块等情况,导致UTXO不可用,所以需要检查UTXO对应的交易是否有效 func (store *privacyStore) moveFTXO2UTXO(key1 []byte, newbatch db.Batch) { @@ -881,8 +881,8 @@ func (store *privacyStore) unsetUTXO(assetExec, token, addr, txhash string, outi return nil } -//由于块的回退的原因,导致其中的交易需要被回退,即将stxo回退到ftxo, -//正常情况下,被回退的交易会被重新加入到新的区块中并得到执行 +// 由于块的回退的原因,导致其中的交易需要被回退,即将stxo回退到ftxo, +// 正常情况下,被回退的交易会被重新加入到新的区块中并得到执行 func (store *privacyStore) moveSTXO2FTXO(tx *types.Transaction, txhash string, newbatch db.Batch) error { //设置ftxo的key,使其能够方便地获取到对应的交易花费的utxo key2 := calcKey4STXOsInTx(txhash) diff --git a/plugin/dapp/privacy/wallet/util.go b/plugin/dapp/privacy/wallet/util.go index 7ffcd23c79..286fb30f0d 100644 --- a/plugin/dapp/privacy/wallet/util.go +++ b/plugin/dapp/privacy/wallet/util.go @@ -32,7 +32,7 @@ func makeViewSpendPubKeyPairToString(viewPubKey, spendPubKey []byte) string { return hex.EncodeToString(pair) } -//将amount切分为1,2,5的组合,这样在进行amount混淆的时候就能够方便获取相同额度的utxo +// 将amount切分为1,2,5的组合,这样在进行amount混淆的时候就能够方便获取相同额度的utxo func decomAmount2Nature(amount int64, order int64) []int64 { res := make([]int64, 0) if order == 0 { @@ -68,7 +68,7 @@ func decomAmount2Nature(amount int64, order int64) []int64 { } // 62387455827 -> 455827 + 7000000 + 80000000 + 300000000 + 2000000000 + 60000000000, where 455827 <= dustThreshold -//res:[455827, 7000000, 80000000, 300000000, 2000000000, 60000000000] +// res:[455827, 7000000, 80000000, 300000000, 2000000000, 60000000000] func decomposeAmount2digits(amount, dustThreshold int64) []int64 { res := make([]int64, 0) if 0 >= amount { @@ -157,9 +157,9 @@ func parseViewSpendPubKeyPair(in string) (viewPubKey, spendPubKey []byte, err er // return &privacyOutput, nil //} -//最后构造完成的utxo依次是2种类型,不构造交易费utxo,使其直接燃烧消失 -//1.进行实际转账utxo -//2.进行找零转账utxo +// 最后构造完成的utxo依次是2种类型,不构造交易费utxo,使其直接燃烧消失 +// 1.进行实际转账utxo +// 2.进行找零转账utxo func generateOuts(viewpubTo, spendpubto, viewpubChangeto, spendpubChangeto *[32]byte, transAmount, selectedAmount, fee, coinPrecision int64) (*privacytypes.PrivacyOutput, error) { decomDigit := decomposeAmount2digits(transAmount, privacytypes.BTYDustThreshold*coinPrecision) //计算找零 diff --git a/plugin/dapp/qbftNode/commands/qbftNode.go b/plugin/dapp/qbftNode/commands/qbftNode.go index cb58ded287..d686585700 100644 --- a/plugin/dapp/qbftNode/commands/qbftNode.go +++ b/plugin/dapp/qbftNode/commands/qbftNode.go @@ -237,7 +237,7 @@ func addNode(cmd *cobra.Command, args []string) { fmt.Println(hex.EncodeToString(txHex)) } -//CreateCmd to create keyfiles +// CreateCmd to create keyfiles func CreateCmd() *cobra.Command { cmd := &cobra.Command{ Use: "gen_file", diff --git a/plugin/dapp/qbftNode/executor/qbftNode.go b/plugin/dapp/qbftNode/executor/qbftNode.go index ecddb494a5..85677f4f6d 100644 --- a/plugin/dapp/qbftNode/executor/qbftNode.go +++ b/plugin/dapp/qbftNode/executor/qbftNode.go @@ -22,7 +22,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&QbftNode{})) diff --git a/plugin/dapp/qbftNode/types/qbftNode.go b/plugin/dapp/qbftNode/types/qbftNode.go index 32f516b93f..1ef9b7b5e7 100644 --- a/plugin/dapp/qbftNode/types/qbftNode.go +++ b/plugin/dapp/qbftNode/types/qbftNode.go @@ -20,12 +20,12 @@ func init() { types.RegExec(QbftNodeX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(QbftNodeX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(QbftNodeX, NewType(cfg)) } diff --git a/plugin/dapp/relay/executor/relay.go b/plugin/dapp/relay/executor/relay.go index fb19027816..18a5227a6f 100644 --- a/plugin/dapp/relay/executor/relay.go +++ b/plugin/dapp/relay/executor/relay.go @@ -22,7 +22,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&relay{})) diff --git a/plugin/dapp/relay/executor/relay_test.go b/plugin/dapp/relay/executor/relay_test.go index 8f0b4a6d2c..77cf02dcdc 100644 --- a/plugin/dapp/relay/executor/relay_test.go +++ b/plugin/dapp/relay/executor/relay_test.go @@ -124,7 +124,7 @@ func (s *suiteRelay) testExecDelLocal(tx *types.Transaction, receipt *types.Rece s.Subset(set.KV, kv) } -//create sell +// create sell func (s *suiteRelay) TestExec_1() { order := &ty.RelayCreate{ Operation: ty.RelayOrderSell, @@ -171,7 +171,7 @@ func (s *suiteRelay) TestExec_1() { } -//accept +// accept func (s *suiteRelay) TestExec_2() { order := &ty.RelayAccept{ OrderId: s.orderID, @@ -208,7 +208,7 @@ func (s *suiteRelay) TestExec_2() { } -//confirm +// confirm func (s *suiteRelay) TestExec_3() { order := &ty.RelayConfirmTx{ @@ -445,7 +445,7 @@ func (s *suiteBtcHeader) testExecBtcHeadDelLocal(tx *types.Transaction, receipt s.Subset(set.KV, kv) } -//rcv btchead +// rcv btchead func (s *suiteBtcHeader) TestSaveBtcHead_1() { head0 := &ty.BtcHeader{ Hash: "5e7d9c599cd040ec2ba53f4dee28028710be8c135e779f65c56feadaae34c3f2", diff --git a/plugin/dapp/relay/executor/relaydb_test.go b/plugin/dapp/relay/executor/relaydb_test.go index 5f45c64d0d..fdddaefef5 100644 --- a/plugin/dapp/relay/executor/relaydb_test.go +++ b/plugin/dapp/relay/executor/relaydb_test.go @@ -80,17 +80,17 @@ func (s *suiteRelayLog) TestReceiptLog() { s.Equal(s.log.Id, log.OrderId) } -////////////////////////////////////////////////// +// //////////////////////////////////////////////// var ( addrFrom = "14KEKbYtKKQm4wMthSK9J4La4nAiidGozt" addrTo = "1Mcx9PczwPQ79tDnYzw62SEQifPwXH84yN" addrBtc = "1Am9UTGfdnxabvcywYG2hvzr6qK8T3oUZT" ) -//fromaddr 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt +// fromaddr 14KEKbYtKKQm4wMthSK9J4La4nAiidGozt var privFrom = getprivkey("CC38546E9E659D15E6B4893F0AB32A06D103931A8230B0BDE71459D2B27D6944") -//to 1Mcx9PczwPQ79tDnYzw62SEQifPwXH84yN +// to 1Mcx9PczwPQ79tDnYzw62SEQifPwXH84yN var privTo = getprivkey("BC38546E9E659D15E6B4893F0AB32A06D103931A8230B0BDE71459D2B27D6944") func getprivkey(key string) crypto.PrivKey { @@ -1203,7 +1203,7 @@ func (s *suiteSaveBtcHeader) TestSaveBtcHeader_1() { } } -//not continuous +// not continuous func (s *suiteSaveBtcHeader) TestSaveBtcHeader_2() { head3 := &ty.BtcHeader{ Hash: "16ad6d588aeca12bf3e7fd6b2263992b4442c9692f4e134ba7cf0d791746328a", @@ -1239,7 +1239,7 @@ func (s *suiteSaveBtcHeader) TestSaveBtcHeader_2() { } -//not continuous than previous +// not continuous than previous func (s *suiteSaveBtcHeader) TestSaveBtcHeader_3() { head3 := &ty.BtcHeader{ Hash: "16ad6d588aeca12bf3e7fd6b2263992b4442c9692f4e134ba7cf0d791746328a", @@ -1282,7 +1282,7 @@ func (s *suiteSaveBtcHeader) TestSaveBtcHeader_3() { } -//reset +// reset func (s *suiteSaveBtcHeader) TestSaveBtcHeader_4() { head4 := &ty.BtcHeader{ diff --git a/plugin/dapp/relay/types/relay.go b/plugin/dapp/relay/types/relay.go index b07fb0a1f0..edbfb491b7 100644 --- a/plugin/dapp/relay/types/relay.go +++ b/plugin/dapp/relay/types/relay.go @@ -20,8 +20,8 @@ const ( ForkRelayVerifyBtcTx = "ForkRelayVerifyBtcTx" ) -//var tlog = log.New("module", name) -//log for relay +// var tlog = log.New("module", name) +// log for relay const ( TyLogRelayCreate = 350 TyLogRelayRevokeCreate = 351 @@ -60,13 +60,13 @@ func init() { types.RegExec(RelayX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(RelayX, "Enable", 0) cfg.RegisterDappFork(RelayX, ForkRelayVerifyBtcTx, 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(RelayX, NewType(cfg)) } diff --git a/plugin/dapp/relay/types/relay.pb.go b/plugin/dapp/relay/types/relay.pb.go index 940f92b56e..5c16fbb1aa 100644 --- a/plugin/dapp/relay/types/relay.pb.go +++ b/plugin/dapp/relay/types/relay.pb.go @@ -676,7 +676,7 @@ func (x *RelayRevoke) GetAction() uint32 { return 0 } -//客户只用交易hash提交, 验证需要的其他信息由relayd提供 +// 客户只用交易hash提交, 验证需要的其他信息由relayd提供 type RelayConfirmTx struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/retrieve/executor/retrieve.go b/plugin/dapp/retrieve/executor/retrieve.go index 5d7beedfe0..bc9e0d4f90 100755 --- a/plugin/dapp/retrieve/executor/retrieve.go +++ b/plugin/dapp/retrieve/executor/retrieve.go @@ -29,13 +29,13 @@ var ( var driverName = "retrieve" -//Init retrieve +// Init retrieve func Init(name string, cfg *types.Chain33Config, sub []byte) { drivers.Register(cfg, GetName(), newRetrieve, cfg.GetDappFork(driverName, "Enable")) InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Retrieve{})) diff --git a/plugin/dapp/retrieve/executor/retrieve_unit_test.go b/plugin/dapp/retrieve/executor/retrieve_unit_test.go index a0069bc47f..63dd91c0a4 100755 --- a/plugin/dapp/retrieve/executor/retrieve_unit_test.go +++ b/plugin/dapp/retrieve/executor/retrieve_unit_test.go @@ -78,7 +78,7 @@ func TestExecPrepare(t *testing.T) { } } -//timelimit +// timelimit func TestExecPerform(t *testing.T) { var targetReceipt types.Receipt var targetErr = rt.ErrRetrievePeriodLimit diff --git a/plugin/dapp/retrieve/types/const.go b/plugin/dapp/retrieve/types/const.go index 67ab93c379..832b15bde2 100755 --- a/plugin/dapp/retrieve/types/const.go +++ b/plugin/dapp/retrieve/types/const.go @@ -4,7 +4,7 @@ package types -//retrieve +// retrieve const ( RetrieveBackup = iota + 1 RetrievePreapre diff --git a/plugin/dapp/retrieve/types/types.go b/plugin/dapp/retrieve/types/types.go index 9cae71fa84..6af6f2d197 100755 --- a/plugin/dapp/retrieve/types/types.go +++ b/plugin/dapp/retrieve/types/types.go @@ -17,14 +17,14 @@ func init() { types.RegExec(RetrieveX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(RetrieveX, "Enable", 0) cfg.RegisterDappFork(RetrieveX, ForkRetriveX, 0) cfg.RegisterDappFork(RetrieveX, ForkRetriveAssetX, 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(RetrieveX, NewType(cfg)) } diff --git a/plugin/dapp/rgbx/commands/commands.go b/plugin/dapp/rgbx/commands/commands.go index 5dbbcc3f5e..a2075b553c 100644 --- a/plugin/dapp/rgbx/commands/commands.go +++ b/plugin/dapp/rgbx/commands/commands.go @@ -3,6 +3,7 @@ package commands import ( "encoding/json" + jsonrpc "github.com/33cn/chain33/rpc/jsonclient" rpctypes "github.com/33cn/chain33/rpc/types" "github.com/33cn/chain33/types" diff --git a/plugin/dapp/rgbx/executor/exec_local_test.go b/plugin/dapp/rgbx/executor/exec_local_test.go index 5f15e83d03..e75b0b0545 100644 --- a/plugin/dapp/rgbx/executor/exec_local_test.go +++ b/plugin/dapp/rgbx/executor/exec_local_test.go @@ -16,6 +16,7 @@ func testSetKV(t *testing.T, db db.DB, kvSet *types.LocalDBSet, del bool) { for _, kv := range kvSet.GetKV() { if !del { err = db.Set(kv.Key, kv.Value) + require.Nil(t, err) continue } if kv.Value == nil { diff --git a/plugin/dapp/rgbx/executor/query_test.go b/plugin/dapp/rgbx/executor/query_test.go index 7e84ca57fb..fcbf88cb71 100644 --- a/plugin/dapp/rgbx/executor/query_test.go +++ b/plugin/dapp/rgbx/executor/query_test.go @@ -1,12 +1,13 @@ package executor import ( + "testing" + "github.com/33cn/chain33/client/mocks" "github.com/33cn/chain33/types" "github.com/33cn/chain33/util" rtypes "github.com/33cn/plugin/plugin/dapp/rgbx/types" "github.com/stretchr/testify/require" - "testing" ) func TestRgbx_Query_ListPendingTx(t *testing.T) { @@ -77,6 +78,7 @@ func TestRgbx_Query_GetPendingTx(t *testing.T) { _, err := r.Query(funcName, types.Encode(&rtypes.ReqGetPendingTx{})) require.Equal(t, types.ErrNotFound, err) msg, err := r.Query(funcName, types.Encode(&rtypes.ReqGetPendingTx{Index: 1})) + require.Nil(t, err) require.Equal(t, int64(1), msg.(*rtypes.PendingTx).GetTxIndex()) } @@ -90,6 +92,7 @@ func TestRgbx_Query_GetConfirmedHeight(t *testing.T) { require.Nil(t, err) require.Nil(t, db.Set([]byte(confirmedHeightKey), types.Encode(&types.Int64{Data: 1}))) msg, err := r.Query(funcName, nil) + require.Nil(t, err) require.Equal(t, int64(1), msg.(*types.Int64).GetData()) } @@ -108,6 +111,7 @@ func TestRgbx_Query_GetAsset(t *testing.T) { require.Equal(t, types.ErrNotFound, err) require.Nil(t, db.Set(formatAssetKey("test"), types.Encode(&rtypes.RgbxAsset{Symbol: "test"}))) msg, err := r.Query(funcName, types.Encode(&types.ReqString{Data: "test"})) + require.Nil(t, err) require.Equal(t, "test", msg.(*rtypes.RgbxAsset).Symbol) } diff --git a/plugin/dapp/rgbx/types/address.go b/plugin/dapp/rgbx/types/address.go index 94b039b14f..49281a3f4a 100644 --- a/plugin/dapp/rgbx/types/address.go +++ b/plugin/dapp/rgbx/types/address.go @@ -2,9 +2,10 @@ package types import ( "fmt" - "github.com/btcsuite/btcd/chaincfg/chainhash" "strconv" "strings" + + "github.com/btcsuite/btcd/chaincfg/chainhash" ) // ToString encode to string diff --git a/plugin/dapp/rgbx/types/rgbx.pb.go b/plugin/dapp/rgbx/types/rgbx.pb.go index 5547120138..6c3707ec33 100644 --- a/plugin/dapp/rgbx/types/rgbx.pb.go +++ b/plugin/dapp/rgbx/types/rgbx.pb.go @@ -8,11 +8,12 @@ package types import ( context "context" + reflect "reflect" + sync "sync" + grpc "google.golang.org/grpc" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" ) const ( diff --git a/plugin/dapp/rollup/executor/exec_local.go b/plugin/dapp/rollup/executor/exec_local.go index 0d9f87f07a..62a9fdb570 100644 --- a/plugin/dapp/rollup/executor/exec_local.go +++ b/plugin/dapp/rollup/executor/exec_local.go @@ -18,7 +18,7 @@ func (r *rollup) ExecLocal_CommitBatch(payload *rolluptypes.CheckPoint, tx *type return r.addAutoRollBack(tx, dbSet.KV), nil } -//当区块回滚时,框架支持自动回滚localdb kv,需要对exec-local返回的kv进行封装 +// 当区块回滚时,框架支持自动回滚localdb kv,需要对exec-local返回的kv进行封装 func (r *rollup) addAutoRollBack(tx *types.Transaction, kv []*types.KeyValue) *types.LocalDBSet { dbSet := &types.LocalDBSet{} diff --git a/plugin/dapp/storage/crypto/aes.go b/plugin/dapp/storage/crypto/aes.go index 466b6de57f..d708c1262d 100644 --- a/plugin/dapp/storage/crypto/aes.go +++ b/plugin/dapp/storage/crypto/aes.go @@ -5,19 +5,19 @@ import ( "crypto/cipher" ) -//AES ... +// AES ... type AES struct { key []byte //iv的长度必须等于block块的大小,这里是16字节,固定 iv []byte } -//NewAES 密钥长度为 16,24,32 字节,三种 +// NewAES 密钥长度为 16,24,32 字节,三种 func NewAES(key, iv []byte) *AES { return &AES{key: key, iv: iv} } -//Encrypt ... +// Encrypt ... func (a *AES) Encrypt(origData []byte) ([]byte, error) { block, err := aes.NewCipher(a.key) if err != nil { @@ -34,7 +34,7 @@ func (a *AES) Encrypt(origData []byte) ([]byte, error) { return crypted, nil } -//Decrypt ... +// Decrypt ... func (a *AES) Decrypt(crypted []byte) ([]byte, error) { block, err := aes.NewCipher(a.key) if err != nil { diff --git a/plugin/dapp/storage/crypto/aes_test.go b/plugin/dapp/storage/crypto/aes_test.go index 8f4bb4dd46..b94f4bb0db 100644 --- a/plugin/dapp/storage/crypto/aes_test.go +++ b/plugin/dapp/storage/crypto/aes_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" ) -//DES 加解密测试 +// DES 加解密测试 func TestAes(t *testing.T) { aes := NewAES(keys[2], ivs[0]) result, err := aes.Encrypt(contents[1]) diff --git a/plugin/dapp/storage/crypto/crypto.go b/plugin/dapp/storage/crypto/crypto.go index 091d8c1c6f..6108edb7c7 100644 --- a/plugin/dapp/storage/crypto/crypto.go +++ b/plugin/dapp/storage/crypto/crypto.go @@ -2,34 +2,34 @@ package crypto import "bytes" -//Crypto ... +// Crypto ... type Crypto interface { Encrypt(origData []byte) ([]byte, error) Decrypt(crypted []byte) ([]byte, error) } -//ZeroPadding ... +// ZeroPadding ... func ZeroPadding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{0}, padding) return append(ciphertext, padtext...) } -//ZeroUnPadding ... +// ZeroUnPadding ... func ZeroUnPadding(origData []byte) []byte { return bytes.TrimRightFunc(origData, func(r rune) bool { return r == rune(0) }) } -//PKCS5Padding ... +// PKCS5Padding ... func PKCS5Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } -//PKCS5UnPadding ... +// PKCS5UnPadding ... func PKCS5UnPadding(origData []byte) []byte { length := len(origData) // 去掉最后一个字节 unpadding 次 diff --git a/plugin/dapp/storage/crypto/des.go b/plugin/dapp/storage/crypto/des.go index 5e053e9df2..ca5d8a0aa5 100644 --- a/plugin/dapp/storage/crypto/des.go +++ b/plugin/dapp/storage/crypto/des.go @@ -5,19 +5,19 @@ import ( "crypto/des" ) -//DES ... +// DES ... type DES struct { key []byte //iv的长度必须等于block块的大小 iv []byte } -//NewDES ... +// NewDES ... func NewDES(key, iv []byte) *DES { return &DES{key: key, iv: iv} } -//Encrypt ... +// Encrypt ... func (d *DES) Encrypt(origData []byte) ([]byte, error) { block, err := des.NewCipher(d.key) if err != nil { @@ -33,7 +33,7 @@ func (d *DES) Encrypt(origData []byte) ([]byte, error) { return crypted, nil } -//Decrypt 密钥key长度固定8字节 +// Decrypt 密钥key长度固定8字节 func (d *DES) Decrypt(crypted []byte) ([]byte, error) { block, err := des.NewCipher(d.key) if err != nil { @@ -48,19 +48,19 @@ func (d *DES) Decrypt(crypted []byte) ([]byte, error) { return origData, nil } -//TripleDES ... +// TripleDES ... type TripleDES struct { key []byte //iv的长度必须等于block块的大小 iv []byte } -//NewTripleDES ... +// NewTripleDES ... func NewTripleDES(key, iv []byte) *TripleDES { return &TripleDES{key: key, iv: iv} } -//Encrypt 3DES加密 24字节 +// Encrypt 3DES加密 24字节 func (d *TripleDES) Encrypt(origData []byte) ([]byte, error) { block, err := des.NewTripleDESCipher(d.key) if err != nil { @@ -74,7 +74,7 @@ func (d *TripleDES) Encrypt(origData []byte) ([]byte, error) { return crypted, nil } -//Decrypt 3DES解密 +// Decrypt 3DES解密 func (d *TripleDES) Decrypt(crypted []byte) ([]byte, error) { block, err := des.NewTripleDESCipher(d.key) if err != nil { diff --git a/plugin/dapp/storage/crypto/des_test.go b/plugin/dapp/storage/crypto/des_test.go index cdb134f1b3..0c046ff1df 100644 --- a/plugin/dapp/storage/crypto/des_test.go +++ b/plugin/dapp/storage/crypto/des_test.go @@ -28,7 +28,7 @@ var ( } ) -//DES 加解密测试 +// DES 加解密测试 func TestDes(t *testing.T) { des := NewDES(keys[0], ivs[0]) result, err := des.Encrypt(contents[0]) @@ -43,7 +43,7 @@ func TestDes(t *testing.T) { assert.Equal(t, contents[0], origData) } -//3DES 加解密测试 +// 3DES 加解密测试 func Test3Des(t *testing.T) { des := NewTripleDES(keys[1], ivs[1]) result, err := des.Encrypt(contents[0]) diff --git a/plugin/dapp/storage/executor/exec_local.go b/plugin/dapp/storage/executor/exec_local.go index a3441c219c..24c1efbab8 100644 --- a/plugin/dapp/storage/executor/exec_local.go +++ b/plugin/dapp/storage/executor/exec_local.go @@ -136,7 +136,7 @@ func (s *storage) ExecLocal_EncryptAdd(payload *ety.EncryptNotaryAdd, tx *types. return s.addAutoRollBack(tx, dbSet.KV), nil } -//设置自动回滚 +// 设置自动回滚 func (s *storage) addAutoRollBack(tx *types.Transaction, kv []*types.KeyValue) *types.LocalDBSet { dbSet := &types.LocalDBSet{} diff --git a/plugin/dapp/storage/executor/query.go b/plugin/dapp/storage/executor/query.go index b67b4cee15..8bcbbee71a 100644 --- a/plugin/dapp/storage/executor/query.go +++ b/plugin/dapp/storage/executor/query.go @@ -5,12 +5,12 @@ import ( storagetypes "github.com/33cn/plugin/plugin/dapp/storage/types" ) -//从statedb 读取原始数据 +// 从statedb 读取原始数据 func (s *storage) Query_QueryStorage(in *storagetypes.QueryStorage) (types.Message, error) { return QueryStorage(s.GetStateDB(), s.GetLocalDB(), in.TxHash) } -//通过状态查询ids +// 通过状态查询ids func (s *storage) Query_BatchQueryStorage(in *storagetypes.BatchQueryStorage) (types.Message, error) { return BatchQueryStorage(s.GetStateDB(), s.GetLocalDB(), in) } diff --git a/plugin/dapp/storage/executor/storage.go b/plugin/dapp/storage/executor/storage.go index ae7cdb3b09..f63e3087d4 100644 --- a/plugin/dapp/storage/executor/storage.go +++ b/plugin/dapp/storage/executor/storage.go @@ -51,7 +51,7 @@ func (s *storage) GetDriverName() string { return driverName } -//ExecutorOrder Exec 的时候 同时执行 ExecLocal +// ExecutorOrder Exec 的时候 同时执行 ExecLocal func (s *storage) ExecutorOrder() int64 { cfg := s.GetAPI().GetConfig() if cfg.IsDappFork(s.GetHeight(), storagetypes.StorageX, storagetypes.ForkStorageLocalDB) { diff --git a/plugin/dapp/storage/executor/storage_test.go b/plugin/dapp/storage/executor/storage_test.go index 02da3bd88c..2400212029 100644 --- a/plugin/dapp/storage/executor/storage_test.go +++ b/plugin/dapp/storage/executor/storage_test.go @@ -254,7 +254,7 @@ func CreateTx(action string, message types.Message, priv string, cfg *types.Chai return tx, err } -//模拟区块中交易得执行过程 +// 模拟区块中交易得执行过程 func Exec_Block(t *testing.T, stateDB dbm.DB, kvdb dbm.KVDB, env *execEnv, txs ...*types.Transaction) error { cfg := types.NewChain33Config(types.GetDefaultCfgstring()) cfg.RegisterDappFork(oty.StorageX, oty.ForkStorageLocalDB, 0) diff --git a/plugin/dapp/storage/executor/storagedb.go b/plugin/dapp/storage/executor/storagedb.go index 0e617e90d6..2868a306bc 100644 --- a/plugin/dapp/storage/executor/storagedb.go +++ b/plugin/dapp/storage/executor/storagedb.go @@ -13,7 +13,7 @@ import ( "github.com/golang/protobuf/proto" ) -//StorageAction ... +// StorageAction ... type StorageAction struct { api client.QueueProtocolAPI db dbm.KV @@ -32,13 +32,13 @@ func newStorageAction(s *storage, tx *types.Transaction, index int) *StorageActi s.GetBlockTime(), s.GetHeight(), index} } -//GetKVSet ... +// GetKVSet ... func (s *StorageAction) GetKVSet(payload proto.Message) (kvset []*types.KeyValue) { kvset = append(kvset, &types.KeyValue{Key: Key(common.ToHex(s.txhash)), Value: types.Encode(payload)}) return kvset } -//ContentStorage ... +// ContentStorage ... func (s *StorageAction) ContentStorage(payload *ety.ContentOnlyNotaryStorage) (*types.Receipt, error) { //TODO 这里可以加具体得文本内容限制,超过指定大小的数据不容许写到状态数据库中 @@ -83,7 +83,7 @@ func (s *StorageAction) ContentStorage(payload *ety.ContentOnlyNotaryStorage) (* return receipt, nil } -//HashStorage ... +// HashStorage ... func (s *StorageAction) HashStorage(payload *ety.HashOnlyNotaryStorage) (*types.Receipt, error) { var logs []*types.ReceiptLog var kvs []*types.KeyValue @@ -111,7 +111,7 @@ func (s *StorageAction) HashStorage(payload *ety.HashOnlyNotaryStorage) (*types. return receipt, nil } -//LinkStorage ... +// LinkStorage ... func (s *StorageAction) LinkStorage(payload *ety.LinkNotaryStorage) (*types.Receipt, error) { var logs []*types.ReceiptLog var kvs []*types.KeyValue @@ -138,7 +138,7 @@ func (s *StorageAction) LinkStorage(payload *ety.LinkNotaryStorage) (*types.Rece return receipt, nil } -//EncryptStorage ... +// EncryptStorage ... func (s *StorageAction) EncryptStorage(payload *ety.EncryptNotaryStorage) (*types.Receipt, error) { var logs []*types.ReceiptLog var kvs []*types.KeyValue @@ -165,7 +165,7 @@ func (s *StorageAction) EncryptStorage(payload *ety.EncryptNotaryStorage) (*type return receipt, nil } -//EncryptShareStorage ... +// EncryptShareStorage ... func (s *StorageAction) EncryptShareStorage(payload *ety.EncryptShareNotaryStorage) (*types.Receipt, error) { var logs []*types.ReceiptLog var kvs []*types.KeyValue @@ -192,7 +192,7 @@ func (s *StorageAction) EncryptShareStorage(payload *ety.EncryptShareNotaryStora return receipt, nil } -//EncryptAdd ... +// EncryptAdd ... func (s *StorageAction) EncryptAdd(payload *ety.EncryptNotaryAdd) (*types.Receipt, error) { var logs []*types.ReceiptLog var kvs []*types.KeyValue @@ -233,7 +233,7 @@ func (s *StorageAction) EncryptAdd(payload *ety.EncryptNotaryAdd) (*types.Receip return receipt, nil } -//QueryStorageByTxHash ... +// QueryStorageByTxHash ... func QueryStorageByTxHash(db dbm.KV, txhash string) (*ety.Storage, error) { data, err := db.Get(Key(txhash)) if err != nil { @@ -250,7 +250,7 @@ func QueryStorageByTxHash(db dbm.KV, txhash string) (*ety.Storage, error) { return &storage, nil } -//QueryStorage ... +// QueryStorage ... func QueryStorage(statedb, localdb dbm.KV, txHash string) (*ety.Storage, error) { if txHash == "" { return nil, fmt.Errorf("txhash can't equail nil") @@ -263,7 +263,7 @@ func QueryStorage(statedb, localdb dbm.KV, txHash string) (*ety.Storage, error) return storage, nil } -//BatchQueryStorage ... +// BatchQueryStorage ... func BatchQueryStorage(statedb, localdb dbm.KV, in *ety.BatchQueryStorage) (types.Message, error) { if len(in.TxHashs) > 10 { return nil, fmt.Errorf("The number of batch queries is too large! the maximux is %d,but current num %d", 10, len(in.TxHashs)) @@ -279,7 +279,7 @@ func BatchQueryStorage(statedb, localdb dbm.KV, in *ety.BatchQueryStorage) (type return &storage, nil } -//QueryStorageFromLocalDB 因为table表不支持嵌套多种数据存储结构,改成手动KV存储 +// QueryStorageFromLocalDB 因为table表不支持嵌套多种数据存储结构,改成手动KV存储 func QueryStorageFromLocalDB(localdb dbm.KV, key string) (*ety.Storage, error) { data, err := localdb.Get(getLocalDBKey(key)) if err != nil { diff --git a/plugin/dapp/storage/types/storage.go b/plugin/dapp/storage/types/storage.go index 27be5786e5..d422234c19 100644 --- a/plugin/dapp/storage/types/storage.go +++ b/plugin/dapp/storage/types/storage.go @@ -44,13 +44,13 @@ const ( TyEncryptAddLog ) -//storage op +// storage op const ( OpCreate = int32(iota) OpAdd ) -//fork +// fork var ( ForkStorageLocalDB = "ForkStorageLocalDB" ) @@ -96,12 +96,12 @@ func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(StorageX, NewType(cfg)) } -//StorageType ... +// StorageType ... type StorageType struct { types.ExecTypeBase } -//NewType ... +// NewType ... func NewType(cfg *types.Chain33Config) *StorageType { c := &StorageType{} c.SetChild(c) diff --git a/plugin/dapp/storage/types/storage.pb.go b/plugin/dapp/storage/types/storage.pb.go index 56293dbdd9..2503dcbbd2 100644 --- a/plugin/dapp/storage/types/storage.pb.go +++ b/plugin/dapp/storage/types/storage.pb.go @@ -23,7 +23,7 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -//后面如果有其他数据模型可继续往上面添加 +// 后面如果有其他数据模型可继续往上面添加 type Storage struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -388,7 +388,7 @@ func (x *ContentOnlyNotaryStorage) GetValue() string { return "" } -//哈希存证模型,推荐使用sha256哈希,限制256位得摘要值 +// 哈希存证模型,推荐使用sha256哈希,限制256位得摘要值 type HashOnlyNotaryStorage struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -759,7 +759,7 @@ func (x *EncryptNotaryAdd) GetEncryptAdd() []byte { return nil } -//根据txhash去状态数据库中查询存储内容 +// 根据txhash去状态数据库中查询存储内容 type QueryStorage struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -807,7 +807,7 @@ func (x *QueryStorage) GetTxHash() string { return "" } -//批量查询有可能导致数据库崩溃 +// 批量查询有可能导致数据库崩溃 type BatchQueryStorage struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/ticket/executor/ticket.go b/plugin/dapp/ticket/executor/ticket.go index 8fb7d6cbd3..ce23948803 100644 --- a/plugin/dapp/ticket/executor/ticket.go +++ b/plugin/dapp/ticket/executor/ticket.go @@ -38,7 +38,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Ticket{})) diff --git a/plugin/dapp/ticket/types/ticket.go b/plugin/dapp/ticket/types/ticket.go index 595af1721c..20f8f97ec4 100755 --- a/plugin/dapp/ticket/types/ticket.go +++ b/plugin/dapp/ticket/types/ticket.go @@ -38,7 +38,7 @@ const ( TyLogTicketBind = 114 ) -//ticket +// ticket const ( // TicketActionGenesis action type TicketActionGenesis = 11 @@ -75,14 +75,14 @@ func init() { } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(TicketX, "Enable", 0) cfg.RegisterDappFork(TicketX, "ForkTicketId", 0) cfg.RegisterDappFork(TicketX, "ForkTicketVrf", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(TicketX, NewType(cfg)) } diff --git a/plugin/dapp/ticket/wallet/keys.go b/plugin/dapp/ticket/wallet/keys.go index cb9fb4bacd..778ecc134b 100644 --- a/plugin/dapp/ticket/wallet/keys.go +++ b/plugin/dapp/ticket/wallet/keys.go @@ -8,7 +8,7 @@ const ( keyWalletAutoMiner = "WalletAutoMiner" ) -//CalcWalletAutoMiner calculate wallet auto miner +// CalcWalletAutoMiner calculate wallet auto miner func CalcWalletAutoMiner() []byte { return []byte(keyWalletAutoMiner) } diff --git a/plugin/dapp/ticket/wallet/ticketstore.go b/plugin/dapp/ticket/wallet/ticketstore.go index cf4484be85..1be7fc77bf 100644 --- a/plugin/dapp/ticket/wallet/ticketstore.go +++ b/plugin/dapp/ticket/wallet/ticketstore.go @@ -9,7 +9,7 @@ import ( wcom "github.com/33cn/chain33/wallet/common" ) -//newStore new storage +// newStore new storage func newStore(db db.DB) *ticketStore { return &ticketStore{Store: wcom.NewStore(db)} } diff --git a/plugin/dapp/token/cmd/signatory-server/signatory/config.pb.go b/plugin/dapp/token/cmd/signatory-server/signatory/config.pb.go index 09cda897ec..80cba0381e 100644 --- a/plugin/dapp/token/cmd/signatory-server/signatory/config.pb.go +++ b/plugin/dapp/token/cmd/signatory-server/signatory/config.pb.go @@ -5,9 +5,11 @@ Package signatory is a generated protocol buffer package. It is generated from these files: + config.proto It has these top-level messages: + Config */ package signatory diff --git a/plugin/dapp/token/executor/kv.go b/plugin/dapp/token/executor/kv.go index 53a531c513..861e86af46 100644 --- a/plugin/dapp/token/executor/kv.go +++ b/plugin/dapp/token/executor/kv.go @@ -52,7 +52,7 @@ func calcTokenStatusTokenKeyPrefixLocal(status int32, token string) []byte { return []byte(fmt.Sprintf(tokenPreCreatedSTONewLocal+"%d-%s-", status, token)) } -//存储地址上收币的信息 +// 存储地址上收币的信息 func calcAddrKey(token string, addr string) []byte { return []byte(fmt.Sprintf("LODB-token-%s-Addr:%s", token, address.FormatAddrKey(addr))) } diff --git a/plugin/dapp/token/executor/token.go b/plugin/dapp/token/executor/token.go index 6a9b433e56..f5d352c5ae 100644 --- a/plugin/dapp/token/executor/token.go +++ b/plugin/dapp/token/executor/token.go @@ -52,7 +52,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&token{})) diff --git a/plugin/dapp/token/executor/token_new_test.go b/plugin/dapp/token/executor/token_new_test.go index f067e6ea3f..da2149a25a 100644 --- a/plugin/dapp/token/executor/token_new_test.go +++ b/plugin/dapp/token/executor/token_new_test.go @@ -50,7 +50,7 @@ const ( fee = 1e6 ) -//for token +// for token var ( tokenName = "NEW" tokenSym = "NEW" diff --git a/plugin/dapp/token/rpc/rpc.go b/plugin/dapp/token/rpc/rpc.go index 53af8497aa..bed1704bcb 100644 --- a/plugin/dapp/token/rpc/rpc.go +++ b/plugin/dapp/token/rpc/rpc.go @@ -15,7 +15,7 @@ import ( context "golang.org/x/net/context" ) -//TODO:和GetBalance进行泛化处理,同时LoadAccounts和LoadExecAccountQueue也需要进行泛化处理, added by hzj +// TODO:和GetBalance进行泛化处理,同时LoadAccounts和LoadExecAccountQueue也需要进行泛化处理, added by hzj func (c *channelClient) getTokenBalance(in *tokenty.ReqTokenBalance) ([]*types.Account, error) { cfg := c.GetConfig() accountTokendb, err := account.NewAccountDB(cfg, tokenty.TokenX, in.GetTokenSymbol(), nil) diff --git a/plugin/dapp/token/types/token.pb.go b/plugin/dapp/token/types/token.pb.go index 2f1bb05805..bb95444a2e 100644 --- a/plugin/dapp/token/types/token.pb.go +++ b/plugin/dapp/token/types/token.pb.go @@ -213,7 +213,7 @@ func (*TokenAction_TokenMint) isTokenAction_Value() {} func (*TokenAction_TokenBurn) isTokenAction_Value() {} -//创建token,支持最大精确度是8位小数,即存入数据库的实际总额需要放大1e8倍 +// 创建token,支持最大精确度是8位小数,即存入数据库的实际总额需要放大1e8倍 type TokenPreCreate struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/token/types/types.go b/plugin/dapp/token/types/types.go index fe06448c99..1bdf883020 100644 --- a/plugin/dapp/token/types/types.go +++ b/plugin/dapp/token/types/types.go @@ -21,7 +21,7 @@ func init() { types.RegExec(TokenX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(TokenX, "Enable", 0) cfg.RegisterDappFork(TokenX, ForkTokenBlackListX, 0) @@ -32,7 +32,7 @@ func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(TokenX, ForkTokenEvm, 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(TokenX, NewType(cfg)) } diff --git a/plugin/dapp/trade/executor/local_order.go b/plugin/dapp/trade/executor/local_order.go index 1e6102efb8..d23892a430 100644 --- a/plugin/dapp/trade/executor/local_order.go +++ b/plugin/dapp/trade/executor/local_order.go @@ -18,11 +18,11 @@ import ( /* 现有接口 - 1. 查询地址对应的买单 (无分页) - 1.1 只指定地址 -> owner - 1.2 同时指定地址和token -> owner_asset - 1.3 显示一个用户成交的所有买单 -> owner - 1.4 显示一个用户成交的指定一个或者多个token所有买单 -> owner_asset 不支持多个 + 1. 查询地址对应的买单 (无分页) + 1.1 只指定地址 -> owner + 1.2 同时指定地址和token -> owner_asset + 1.3 显示一个用户成交的所有买单 -> owner + 1.4 显示一个用户成交的指定一个或者多个token所有买单 -> owner_asset 不支持多个 2. 分状态查询地址的买单: 状态 地址 (无分页) -> owner_status 3. 显示一个token 指定数量的买单 GetTokenBuyOrderByStatus -> asset_inBuy_status 4. 显示指定token出售者的一个或多个token 或 不指定token 的卖单 (无分页) -> owner_asset/owner_asset_isSell 不支持多个 @@ -142,8 +142,9 @@ func (r *OrderRow) isFinished() int { } // status: 设计为可以同时查询几种的并集 , 存储为前缀, 需要提前设计需要合并的, 用前缀表示 -// 进行中, 撤销, 部分成交 , 全部成交, 完成状态统一前缀. 数字和原来不一样 -// 01 10 11 12 19 -> 1* +// +// 进行中, 撤销, 部分成交 , 全部成交, 完成状态统一前缀. 数字和原来不一样 +// 01 10 11 12 19 -> 1* func (r *OrderRow) status() string { if r.Status == pty.TradeOrderStatusOnBuy || r.Status == pty.TradeOrderStatusOnSale { return "01" // 试图用1 可以匹配所有完成的 diff --git a/plugin/dapp/trade/executor/local_order_v2.go b/plugin/dapp/trade/executor/local_order_v2.go index b811b1a820..62004ca9e4 100644 --- a/plugin/dapp/trade/executor/local_order_v2.go +++ b/plugin/dapp/trade/executor/local_order_v2.go @@ -36,7 +36,6 @@ import ( 7. 根据状态分页列出某地址的订单(包括买单卖单) owner_status */ -// var optV2 = &table.Option{ Prefix: "LODB-trade", Name: "order_v2", @@ -109,7 +108,7 @@ func (r *OrderV2Row) Get(key string) ([]byte, error) { case "asset_isSell_status": return []byte(fmt.Sprintf("%s_%d_%s", r.asset(), r.isSell(), r.status())), nil case "owner": - return []byte(address.FormatAddrKey(r.Owner)), nil + return address.FormatAddrKey(r.Owner), nil case "owner_asset": return []byte(fmt.Sprintf("%s_%s", address.FormatAddrKey(r.Owner), r.asset())), nil case "owner_asset_isSell": @@ -166,8 +165,9 @@ func (r *OrderV2Row) price() string { } // status: 设计为可以同时查询几种的并集 , 存储为前缀, 需要提前设计需要合并的, 用前缀表示 -// 进行中, 撤销, 部分成交 , 全部成交, 完成状态统一前缀. 数字和原来不一样 -// 01 10 11 12 19 -> 1* +// +// 进行中, 撤销, 部分成交 , 全部成交, 完成状态统一前缀. 数字和原来不一样 +// 01 10 11 12 19 -> 1* func (r *OrderV2Row) status() string { if r.Status == pty.TradeOrderStatusOnBuy || r.Status == pty.TradeOrderStatusOnSale { return "01" // 试图用1 可以匹配所有完成的 diff --git a/plugin/dapp/trade/executor/trade.go b/plugin/dapp/trade/executor/trade.go index 8d8b464e68..145f679fb6 100644 --- a/plugin/dapp/trade/executor/trade.go +++ b/plugin/dapp/trade/executor/trade.go @@ -38,7 +38,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&trade{})) diff --git a/plugin/dapp/trade/executor/tradedb.go b/plugin/dapp/trade/executor/tradedb.go index 90d3988f5e..0825c5d117 100644 --- a/plugin/dapp/trade/executor/tradedb.go +++ b/plugin/dapp/trade/executor/tradedb.go @@ -430,8 +430,8 @@ func (action *tradeAction) tradeRevokeSell(revoke *pty.TradeForRevokeSell) (*typ return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil } -//不同合约之间查询的需求后面要考虑,现在先重复处理一下,原则上不能直接引用其他合约的代码 -//后面可能会有一套查询规则 和 写规则, 合约对其他合约只读 +// 不同合约之间查询的需求后面要考虑,现在先重复处理一下,原则上不能直接引用其他合约的代码 +// 后面可能会有一套查询规则 和 写规则, 合约对其他合约只读 func calcTokenKey(token string) (key []byte) { tokenCreated := "mavl-token-" return []byte(fmt.Sprintf(tokenCreated+"%s", token)) diff --git a/plugin/dapp/trade/executor/util.go b/plugin/dapp/trade/executor/util.go index 37db0bf868..c6dc6ec9b2 100644 --- a/plugin/dapp/trade/executor/util.go +++ b/plugin/dapp/trade/executor/util.go @@ -26,7 +26,7 @@ import ( */ -//GetExecSymbol : return exec, symbol +// GetExecSymbol : return exec, symbol func GetExecSymbol(order *pt.SellOrder) (string, string) { if order.AssetExec == "" { return defaultAssetExec, defaultAssetExec + "." + order.TokenSymbol diff --git a/plugin/dapp/trade/rpc/jrpc.go b/plugin/dapp/trade/rpc/jrpc.go index a2e4161ec9..f4a4d58477 100644 --- a/plugin/dapp/trade/rpc/jrpc.go +++ b/plugin/dapp/trade/rpc/jrpc.go @@ -13,7 +13,7 @@ import ( ptypes "github.com/33cn/plugin/plugin/dapp/trade/types" ) -//CreateRawTradeSellTx : 创建出售token的未签名交易 +// CreateRawTradeSellTx : 创建出售token的未签名交易 func (jrpc *Jrpc) CreateRawTradeSellTx(in *ptypes.TradeSellTx, result *interface{}) error { if in == nil { return types.ErrInvalidParam @@ -40,7 +40,7 @@ func (jrpc *Jrpc) CreateRawTradeSellTx(in *ptypes.TradeSellTx, result *interface return nil } -//CreateRawTradeBuyTx : 创建购买token的未签名交易,向指定卖单发起购买 +// CreateRawTradeBuyTx : 创建购买token的未签名交易,向指定卖单发起购买 func (jrpc *Jrpc) CreateRawTradeBuyTx(in *ptypes.TradeBuyTx, result *interface{}) error { if in == nil { return types.ErrInvalidParam @@ -58,7 +58,7 @@ func (jrpc *Jrpc) CreateRawTradeBuyTx(in *ptypes.TradeBuyTx, result *interface{} return nil } -//CreateRawTradeRevokeTx : 取消指定卖单 +// CreateRawTradeRevokeTx : 取消指定卖单 func (jrpc *Jrpc) CreateRawTradeRevokeTx(in *ptypes.TradeRevokeTx, result *interface{}) error { if in == nil { return types.ErrInvalidParam @@ -75,7 +75,7 @@ func (jrpc *Jrpc) CreateRawTradeRevokeTx(in *ptypes.TradeRevokeTx, result *inter return nil } -//CreateRawTradeBuyLimitTx : 挂买单购买token +// CreateRawTradeBuyLimitTx : 挂买单购买token func (jrpc *Jrpc) CreateRawTradeBuyLimitTx(in *ptypes.TradeBuyLimitTx, result *interface{}) error { if in == nil { return types.ErrInvalidParam @@ -99,7 +99,7 @@ func (jrpc *Jrpc) CreateRawTradeBuyLimitTx(in *ptypes.TradeBuyLimitTx, result *i return nil } -//CreateRawTradeSellMarketTx : 向指定买单出售token +// CreateRawTradeSellMarketTx : 向指定买单出售token func (jrpc *Jrpc) CreateRawTradeSellMarketTx(in *ptypes.TradeSellMarketTx, result *interface{}) error { if in == nil { return types.ErrInvalidParam @@ -117,7 +117,7 @@ func (jrpc *Jrpc) CreateRawTradeSellMarketTx(in *ptypes.TradeSellMarketTx, resul return nil } -//CreateRawTradeRevokeBuyTx : 取消指定买单 +// CreateRawTradeRevokeBuyTx : 取消指定买单 func (jrpc *Jrpc) CreateRawTradeRevokeBuyTx(in *ptypes.TradeRevokeBuyTx, result *interface{}) error { if in == nil { return types.ErrInvalidParam diff --git a/plugin/dapp/trade/rpc/rpc.go b/plugin/dapp/trade/rpc/rpc.go index 58281ba06e..3541cae813 100644 --- a/plugin/dapp/trade/rpc/rpc.go +++ b/plugin/dapp/trade/rpc/rpc.go @@ -11,7 +11,7 @@ import ( ptypes "github.com/33cn/plugin/plugin/dapp/trade/types" ) -//CreateRawTradeSellTx : +// CreateRawTradeSellTx : func (cc *channelClient) CreateRawTradeSellTx(ctx context.Context, in *ptypes.TradeForSell) (*types.UnsignTx, error) { if in == nil { return nil, types.ErrInvalidParam @@ -29,7 +29,7 @@ func (cc *channelClient) CreateRawTradeSellTx(ctx context.Context, in *ptypes.Tr return &types.UnsignTx{Data: data}, nil } -//CreateRawTradeBuyTx : +// CreateRawTradeBuyTx : func (cc *channelClient) CreateRawTradeBuyTx(ctx context.Context, in *ptypes.TradeForBuy) (*types.UnsignTx, error) { if in == nil { return nil, types.ErrInvalidParam @@ -47,7 +47,7 @@ func (cc *channelClient) CreateRawTradeBuyTx(ctx context.Context, in *ptypes.Tra return &types.UnsignTx{Data: data}, nil } -//CreateRawTradeRevokeTx : +// CreateRawTradeRevokeTx : func (cc *channelClient) CreateRawTradeRevokeTx(ctx context.Context, in *ptypes.TradeForRevokeSell) (*types.UnsignTx, error) { if in == nil { return nil, types.ErrInvalidParam @@ -65,7 +65,7 @@ func (cc *channelClient) CreateRawTradeRevokeTx(ctx context.Context, in *ptypes. return &types.UnsignTx{Data: data}, nil } -//CreateRawTradeBuyLimitTx : +// CreateRawTradeBuyLimitTx : func (cc *channelClient) CreateRawTradeBuyLimitTx(ctx context.Context, in *ptypes.TradeForBuyLimit) (*types.UnsignTx, error) { if in == nil { return nil, types.ErrInvalidParam @@ -83,7 +83,7 @@ func (cc *channelClient) CreateRawTradeBuyLimitTx(ctx context.Context, in *ptype return &types.UnsignTx{Data: data}, nil } -//CreateRawTradeSellMarketTx : +// CreateRawTradeSellMarketTx : func (cc *channelClient) CreateRawTradeSellMarketTx(ctx context.Context, in *ptypes.TradeForSellMarket) (*types.UnsignTx, error) { if in == nil { return nil, types.ErrInvalidParam @@ -101,7 +101,7 @@ func (cc *channelClient) CreateRawTradeSellMarketTx(ctx context.Context, in *pty return &types.UnsignTx{Data: data}, nil } -//CreateRawTradeRevokeBuyTx : +// CreateRawTradeRevokeBuyTx : func (cc *channelClient) CreateRawTradeRevokeBuyTx(ctx context.Context, in *ptypes.TradeForRevokeBuy) (*types.UnsignTx, error) { if in == nil { return nil, types.ErrInvalidParam diff --git a/plugin/dapp/trade/rpc/types.go b/plugin/dapp/trade/rpc/types.go index eede60218b..0d21c8d542 100644 --- a/plugin/dapp/trade/rpc/types.go +++ b/plugin/dapp/trade/rpc/types.go @@ -14,17 +14,17 @@ type channelClient struct { rpctypes.ChannelClient } -//Jrpc : Jrpc struct definition +// Jrpc : Jrpc struct definition type Jrpc struct { cli *channelClient } -//Grpc : Grpc struct definition +// Grpc : Grpc struct definition type Grpc struct { *channelClient } -//Init : do the init operation +// Init : do the init operation func Init(name string, s rpctypes.RPCServer) { cli := &channelClient{} grpc := &Grpc{channelClient: cli} @@ -32,7 +32,7 @@ func Init(name string, s rpctypes.RPCServer) { ptypes.RegisterTradeServer(s.GRPC(), grpc) } -//GetLastMemPool : get the last memory pool +// GetLastMemPool : get the last memory pool func (jrpc *Jrpc) GetLastMemPool(in types.ReqNil, result *interface{}) error { reply, err := jrpc.cli.GetLastMempool() if err != nil { diff --git a/plugin/dapp/trade/types/const.go b/plugin/dapp/trade/types/const.go index 9401f33bb9..fcc12e8eb9 100644 --- a/plugin/dapp/trade/types/const.go +++ b/plugin/dapp/trade/types/const.go @@ -40,7 +40,7 @@ const ( TradeOrderStatusGroupComplete ) -//SellOrderStatus : sell order status map +// SellOrderStatus : sell order status map var SellOrderStatus = map[int32]string{ TradeOrderStatusNotStart: "NotStart", TradeOrderStatusOnSale: "OnSale", @@ -52,7 +52,7 @@ var SellOrderStatus = map[int32]string{ TradeOrderStatusBuyRevoked: "BuyRevoked", } -//SellOrderStatus2Int : SellOrderStatus info to value in int32 +// SellOrderStatus2Int : SellOrderStatus info to value in int32 var SellOrderStatus2Int = map[string]int32{ "NotStart": TradeOrderStatusNotStart, "OnSale": TradeOrderStatusOnSale, @@ -64,14 +64,14 @@ var SellOrderStatus2Int = map[string]int32{ "BuyRevoked": TradeOrderStatusBuyRevoked, } -//MapSellOrderStatusStr2Int : +// MapSellOrderStatusStr2Int : var MapSellOrderStatusStr2Int = map[string]int32{ "onsale": TradeOrderStatusOnSale, "soldout": TradeOrderStatusSoldOut, "revoked": TradeOrderStatusRevoked, } -//MapBuyOrderStatusStr2Int : +// MapBuyOrderStatusStr2Int : var MapBuyOrderStatusStr2Int = map[string]int32{ "onbuy": TradeOrderStatusOnBuy, "boughtout": TradeOrderStatusBoughtOut, diff --git a/plugin/dapp/trade/types/trade.go b/plugin/dapp/trade/types/trade.go index 77f1f37a84..a54ff7f825 100644 --- a/plugin/dapp/trade/types/trade.go +++ b/plugin/dapp/trade/types/trade.go @@ -36,17 +36,17 @@ var ( } ) -//GetName ... +// GetName ... func (t *TradeType) GetName() string { return TradeX } -//GetTypeMap ... +// GetTypeMap ... func (t *TradeType) GetTypeMap() map[string]int32 { return actionName } -//GetLogMap ... +// GetLogMap ... func (t *TradeType) GetLogMap() map[int64]*types.LogInfo { return logInfo } @@ -57,7 +57,7 @@ func init() { types.RegExec(TradeX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(TradeX, "Enable", 0) cfg.RegisterDappFork(TradeX, ForkTradeBuyLimitX, 0) @@ -67,17 +67,17 @@ func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(TradeX, ForkTradePriceX, 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(TradeX, NewType(cfg)) } -//TradeType ... +// TradeType ... type TradeType struct { types.ExecTypeBase } -//NewType ... +// NewType ... func NewType(cfg *types.Chain33Config) *TradeType { c := &TradeType{} c.SetChild(c) @@ -85,12 +85,12 @@ func NewType(cfg *types.Chain33Config) *TradeType { return c } -//GetPayload ... +// GetPayload ... func (t *TradeType) GetPayload() types.Message { return &Trade{} } -//ActionName ... +// ActionName ... func (t *TradeType) ActionName(tx *types.Transaction) string { var action Trade err := types.Decode(tx.Payload, &action) @@ -113,7 +113,7 @@ func (t *TradeType) ActionName(tx *types.Transaction) string { return "unknown" } -//Amount ... +// Amount ... func (t *TradeType) Amount(tx *types.Transaction) (int64, error) { //TODO: 补充和完善token和trade分支的amount的计算, added by hzj var trade Trade @@ -132,7 +132,7 @@ func (t *TradeType) Amount(tx *types.Transaction) (int64, error) { return 0, nil } -//CreateTx ... +// CreateTx ... func (t *TradeType) CreateTx(action string, message json.RawMessage) (*types.Transaction, error) { //var tx *types.Transaction cfg := t.GetConfig() @@ -189,7 +189,7 @@ func (t *TradeType) CreateTx(action string, message json.RawMessage) (*types.Tra return nil, types.ErrNotSupport } -//CreateRawTradeSellTx : 创建卖单交易 +// CreateRawTradeSellTx : 创建卖单交易 func CreateRawTradeSellTx(cfg *types.Chain33Config, parm *TradeSellTx) (*types.Transaction, error) { if parm == nil { return nil, types.ErrInvalidParam @@ -214,7 +214,7 @@ func CreateRawTradeSellTx(cfg *types.Chain33Config, parm *TradeSellTx) (*types.T return types.CreateFormatTx(cfg, cfg.ExecName(TradeX), types.Encode(sell)) } -//CreateRawTradeBuyTx :创建想指定卖单发起的买单交易 +// CreateRawTradeBuyTx :创建想指定卖单发起的买单交易 func CreateRawTradeBuyTx(cfg *types.Chain33Config, parm *TradeBuyTx) (*types.Transaction, error) { if parm == nil { return nil, types.ErrInvalidParam @@ -227,7 +227,7 @@ func CreateRawTradeBuyTx(cfg *types.Chain33Config, parm *TradeBuyTx) (*types.Tra return types.CreateFormatTx(cfg, cfg.ExecName(TradeX), types.Encode(buy)) } -//CreateRawTradeRevokeTx :创建取消卖单的交易 +// CreateRawTradeRevokeTx :创建取消卖单的交易 func CreateRawTradeRevokeTx(cfg *types.Chain33Config, parm *TradeRevokeTx) (*types.Transaction, error) { if parm == nil { return nil, types.ErrInvalidParam @@ -241,7 +241,7 @@ func CreateRawTradeRevokeTx(cfg *types.Chain33Config, parm *TradeRevokeTx) (*typ return types.CreateFormatTx(cfg, cfg.ExecName(TradeX), types.Encode(buy)) } -//CreateRawTradeBuyLimitTx :创建买单交易 +// CreateRawTradeBuyLimitTx :创建买单交易 func CreateRawTradeBuyLimitTx(cfg *types.Chain33Config, parm *TradeBuyLimitTx) (*types.Transaction, error) { if parm == nil { return nil, types.ErrInvalidParam @@ -263,7 +263,7 @@ func CreateRawTradeBuyLimitTx(cfg *types.Chain33Config, parm *TradeBuyLimitTx) ( return types.CreateFormatTx(cfg, cfg.ExecName(TradeX), types.Encode(buyLimit)) } -//CreateRawTradeSellMarketTx : 创建向指定买单出售token的卖单交易 +// CreateRawTradeSellMarketTx : 创建向指定买单出售token的卖单交易 func CreateRawTradeSellMarketTx(cfg *types.Chain33Config, parm *TradeSellMarketTx) (*types.Transaction, error) { if parm == nil { return nil, types.ErrInvalidParam @@ -276,7 +276,7 @@ func CreateRawTradeSellMarketTx(cfg *types.Chain33Config, parm *TradeSellMarketT return types.CreateFormatTx(cfg, cfg.ExecName(TradeX), types.Encode(sellMarket)) } -//CreateRawTradeRevokeBuyTx : 取消发起的买单交易 +// CreateRawTradeRevokeBuyTx : 取消发起的买单交易 func CreateRawTradeRevokeBuyTx(cfg *types.Chain33Config, parm *TradeRevokeBuyTx) (*types.Transaction, error) { if parm == nil { return nil, types.ErrInvalidParam diff --git a/plugin/dapp/trade/types/trade.pb.go b/plugin/dapp/trade/types/trade.pb.go index 38aa09b14c..d0b56c9a55 100644 --- a/plugin/dapp/trade/types/trade.pb.go +++ b/plugin/dapp/trade/types/trade.pb.go @@ -27,7 +27,6 @@ const ( ) // trade 交易部分 -// type Trade struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1655,7 +1654,9 @@ func (x *ReqAddrAssets) GetFromKey() string { } // 获取Token未完成卖单的交易列表 -// fromKey : 第一次传参为空,获取卖单单价最低的列表。 当要获得下一页时, +// +// fromKey : 第一次传参为空,获取卖单单价最低的列表。 当要获得下一页时, +// // 传当前页最后一个;当要获得上一页时, 传当前页第一个。 count // :获取交易列表的个数。 direction :查找方式;0,上一页;1,下一页。 // 越靠后的也单价越贵 diff --git a/plugin/dapp/trade/types/tx.go b/plugin/dapp/trade/types/tx.go index 704650fdfa..27adfe651b 100644 --- a/plugin/dapp/trade/types/tx.go +++ b/plugin/dapp/trade/types/tx.go @@ -4,7 +4,7 @@ package types -//TradeSellTx : info for sell order +// TradeSellTx : info for sell order type TradeSellTx struct { TokenSymbol string `json:"tokenSymbol"` AmountPerBoardlot int64 `json:"amountPerBoardlot"` @@ -17,20 +17,20 @@ type TradeSellTx struct { PriceSymbol string `json:"priceSymbol"` } -//TradeBuyTx :info for buy order to speficied order +// TradeBuyTx :info for buy order to speficied order type TradeBuyTx struct { SellID string `json:"sellID"` BoardlotCnt int64 `json:"boardlotCnt"` Fee int64 `json:"fee"` } -//TradeRevokeTx :用于取消卖单的信息 +// TradeRevokeTx :用于取消卖单的信息 type TradeRevokeTx struct { SellID string `json:"sellID,"` Fee int64 `json:"fee"` } -//TradeBuyLimitTx :用于挂买单的信息 +// TradeBuyLimitTx :用于挂买单的信息 type TradeBuyLimitTx struct { TokenSymbol string `json:"tokenSymbol"` AmountPerBoardlot int64 `json:"amountPerBoardlot"` @@ -43,14 +43,14 @@ type TradeBuyLimitTx struct { PriceSymbol string `json:"priceSymbol"` } -//TradeSellMarketTx :用于向指定买单出售token的信息 +// TradeSellMarketTx :用于向指定买单出售token的信息 type TradeSellMarketTx struct { BuyID string `json:"buyID"` BoardlotCnt int64 `json:"boardlotCnt"` Fee int64 `json:"fee"` } -//TradeRevokeBuyTx :取消指定买单 +// TradeRevokeBuyTx :取消指定买单 type TradeRevokeBuyTx struct { BuyID string `json:"buyID,"` Fee int64 `json:"fee"` diff --git a/plugin/dapp/unfreeze/executor/unfreeze.go b/plugin/dapp/unfreeze/executor/unfreeze.go index d8a8a46ec4..07449334f4 100644 --- a/plugin/dapp/unfreeze/executor/unfreeze.go +++ b/plugin/dapp/unfreeze/executor/unfreeze.go @@ -21,7 +21,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&Unfreeze{})) diff --git a/plugin/dapp/valnode/commands/valnode.go b/plugin/dapp/valnode/commands/valnode.go index c87e9cbc94..309290579b 100644 --- a/plugin/dapp/valnode/commands/valnode.go +++ b/plugin/dapp/valnode/commands/valnode.go @@ -190,7 +190,7 @@ func addNode(cmd *cobra.Command, args []string) { fmt.Println(hex.EncodeToString(txHex)) } -//CreateCmd to create keyfiles +// CreateCmd to create keyfiles func CreateCmd() *cobra.Command { cmd := &cobra.Command{ Use: "init_keyfile", diff --git a/plugin/dapp/valnode/executor/valnode.go b/plugin/dapp/valnode/executor/valnode.go index d7624ac6f7..ecedeb9669 100644 --- a/plugin/dapp/valnode/executor/valnode.go +++ b/plugin/dapp/valnode/executor/valnode.go @@ -22,7 +22,7 @@ func Init(name string, cfg *types.Chain33Config, sub []byte) { InitExecType() } -//InitExecType ... +// InitExecType ... func InitExecType() { ety := types.LoadExecutorType(driverName) ety.InitFuncList(types.ListMethod(&ValNode{})) diff --git a/plugin/dapp/valnode/types/valnode.go b/plugin/dapp/valnode/types/valnode.go index 3d5d6d1571..63c8a87fba 100644 --- a/plugin/dapp/valnode/types/valnode.go +++ b/plugin/dapp/valnode/types/valnode.go @@ -22,12 +22,12 @@ func init() { types.RegExec(ValNodeX, InitExecutor) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(ValNodeX, "Enable", 0) } -//InitExecutor ... +// InitExecutor ... func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(ValNodeX, NewType(cfg)) } diff --git a/plugin/dapp/vote/executor/exec_local.go b/plugin/dapp/vote/executor/exec_local.go index 75c11b96f5..3bac50d157 100644 --- a/plugin/dapp/vote/executor/exec_local.go +++ b/plugin/dapp/vote/executor/exec_local.go @@ -178,7 +178,7 @@ func (v *vote) ExecLocal_UpdateMember(payload *vty.UpdateMember, tx *types.Trans return v.addAutoRollBack(tx, dbSet.KV), nil } -//当区块回滚时,框架支持自动回滚localdb kv,需要对exec-local返回的kv进行封装 +// 当区块回滚时,框架支持自动回滚localdb kv,需要对exec-local返回的kv进行封装 func (v *vote) addAutoRollBack(tx *types.Transaction, kv []*types.KeyValue) *types.LocalDBSet { dbSet := &types.LocalDBSet{} @@ -235,7 +235,7 @@ func (v *vote) addGroupMember(groupID string, addrs []string) ([]*types.KeyValue return kvs, nil } -//删除用户,将对应的groupID信息删除 +// 删除用户,将对应的groupID信息删除 func (v *vote) removeGroupMember(groupID string, addrs []string) ([]*types.KeyValue, error) { table := newMemberTable(v.GetLocalDB()) diff --git a/plugin/dapp/vote/executor/table.go b/plugin/dapp/vote/executor/table.go index acb9acf77c..a7e6b2d6b9 100644 --- a/plugin/dapp/vote/executor/table.go +++ b/plugin/dapp/vote/executor/table.go @@ -31,7 +31,7 @@ var memberTableOpt = &table.Option{ Primary: memberTablePrimary, } -//新建表 +// 新建表 func newTable(kvDB db.KV, rowMeta table.RowMeta, opt *table.Option) *table.Table { table, err := table.NewTable(rowMeta, kvDB, opt) if err != nil { @@ -52,17 +52,17 @@ func newMemberTable(kvDB db.KV) *table.Table { return newTable(kvDB, &memberTableRow{}, memberTableOpt) } -//groupTableRow table meta 结构 +// groupTableRow table meta 结构 type groupTableRow struct { *vty.GroupInfo } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (r *groupTableRow) CreateRow() *table.Row { return &table.Row{Data: &vty.GroupInfo{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *groupTableRow) SetPayload(data types.Message) error { if d, ok := data.(*vty.GroupInfo); ok { r.GroupInfo = d @@ -71,7 +71,7 @@ func (r *groupTableRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *groupTableRow) Get(key string) ([]byte, error) { if key == groupTablePrimary { return []byte(r.GroupInfo.GetID()), nil @@ -79,17 +79,17 @@ func (r *groupTableRow) Get(key string) ([]byte, error) { return nil, types.ErrNotFound } -//voteTableRow table meta 结构 +// voteTableRow table meta 结构 type voteTableRow struct { *vty.VoteInfo } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (r *voteTableRow) CreateRow() *table.Row { return &table.Row{Data: &vty.VoteInfo{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *voteTableRow) SetPayload(data types.Message) error { if d, ok := data.(*vty.VoteInfo); ok { r.VoteInfo = d @@ -98,7 +98,7 @@ func (r *voteTableRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *voteTableRow) Get(key string) ([]byte, error) { if key == voteTablePrimary { return []byte(r.VoteInfo.GetID()), nil @@ -112,12 +112,12 @@ type memberTableRow struct { *vty.MemberInfo } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (r *memberTableRow) CreateRow() *table.Row { return &table.Row{Data: &vty.MemberInfo{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *memberTableRow) SetPayload(data types.Message) error { if d, ok := data.(*vty.MemberInfo); ok { r.MemberInfo = d @@ -126,7 +126,7 @@ func (r *memberTableRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *memberTableRow) Get(key string) ([]byte, error) { if key == memberTablePrimary { return []byte(r.MemberInfo.GetAddr()), nil diff --git a/plugin/dapp/vote/types/vote.pb.go b/plugin/dapp/vote/types/vote.pb.go index 5b2ed62d55..1901e43c6c 100644 --- a/plugin/dapp/vote/types/vote.pb.go +++ b/plugin/dapp/vote/types/vote.pb.go @@ -229,7 +229,7 @@ func (x *GroupMember) GetNickName() string { return "" } -//创建投票组 +// 创建投票组 type CreateGroup struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -301,7 +301,7 @@ func (x *CreateGroup) GetDescription() string { return "" } -//更新投票组 +// 更新投票组 type UpdateGroup struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -532,7 +532,7 @@ func (x *GroupInfos) GetGroupList() []*GroupInfo { return nil } -//投票选项 +// 投票选项 type VoteOption struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -889,7 +889,7 @@ func (x *UpdateMember) GetName() string { return "" } -//投票信息 +// 投票信息 type VoteInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1221,7 +1221,7 @@ func (x *ReqStrings) GetItems() []string { return nil } -//列表请求结构 +// 列表请求结构 type ReqListItem struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/wasm/executor/callback.go b/plugin/dapp/wasm/executor/callback.go index d5e2cb5a93..7dcb07999d 100644 --- a/plugin/dapp/wasm/executor/callback.go +++ b/plugin/dapp/wasm/executor/callback.go @@ -7,7 +7,7 @@ import ( types2 "github.com/33cn/plugin/plugin/dapp/wasm/types" ) -//stateDB wrapper +// stateDB wrapper func setStateDB(key, value []byte) { wasmCB.stateKVC.Add(key, value) } @@ -24,7 +24,7 @@ func getStateDB(key []byte) ([]byte, error) { return wasmCB.stateKVC.Get(key) } -//localDB wrapper +// localDB wrapper func setLocalDB(key, value []byte) { wasmCB.localCache = append(wasmCB.localCache, &types2.LocalDataLog{ Key: append(calcLocalPrefix(wasmCB.contractName), key...), @@ -51,7 +51,7 @@ func getLocalDB(key []byte) ([]byte, error) { return wasmCB.GetLocalDB().Get(newKey) } -//account wrapper +// account wrapper func getBalance(addr, execer string) (balance, frozen int64, err error) { accounts, err := wasmCB.GetCoinsAccount().GetBalance(wasmCB.GetAPI(), &types.ReqBalance{ Addresses: []string{addr}, diff --git a/plugin/dapp/x2ethereum/commands/buildflags/flags.go b/plugin/dapp/x2ethereum/commands/buildflags/flags.go index 27682f9f76..1ade5577c9 100644 --- a/plugin/dapp/x2ethereum/commands/buildflags/flags.go +++ b/plugin/dapp/x2ethereum/commands/buildflags/flags.go @@ -4,5 +4,5 @@ package buildflags -//NodeAddr --- +// NodeAddr --- var NodeAddr string diff --git a/plugin/dapp/x2ethereum/commands/commands.go b/plugin/dapp/x2ethereum/commands/commands.go index adeb1d7c34..f78af1fa4b 100644 --- a/plugin/dapp/x2ethereum/commands/commands.go +++ b/plugin/dapp/x2ethereum/commands/commands.go @@ -48,7 +48,7 @@ func Cmd() *cobra.Command { return cmd } -//CreateRawWithdrawChain33TxCmd Burn +// CreateRawWithdrawChain33TxCmd Burn func CreateRawWithdrawChain33TxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "burn", @@ -104,7 +104,7 @@ func burn(cmd *cobra.Command, args []string) { createTx(cmd, payLoad, types3.NameWithdrawChain33Action) } -//CreateRawChain33ToEthTxCmd Lock +// CreateRawChain33ToEthTxCmd Lock func CreateRawChain33ToEthTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "lock", @@ -148,7 +148,7 @@ func lock(cmd *cobra.Command, args []string) { createTx(cmd, payLoad, types3.NameChain33ToEthAction) } -//CreateTransferCmd Transfer +// CreateTransferCmd Transfer func CreateTransferCmd() *cobra.Command { cmd := &cobra.Command{ Use: "transfer", @@ -234,7 +234,7 @@ func createTokenWithdraw(cmd *cobra.Command, args []string) { commands.CreateAssetWithdraw(cmd, args, types3.X2ethereumX) } -//CreateRawAddValidatorTxCmd AddValidator +// CreateRawAddValidatorTxCmd AddValidator func CreateRawAddValidatorTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "add", @@ -267,7 +267,7 @@ func addValidator(cmd *cobra.Command, args []string) { createTx(cmd, payLoad, types3.NameAddValidatorAction) } -//CreateRawRemoveValidatorTxCmd RemoveValidator +// CreateRawRemoveValidatorTxCmd RemoveValidator func CreateRawRemoveValidatorTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "remove", @@ -291,7 +291,7 @@ func removeValidator(cmd *cobra.Command, args []string) { createTx(cmd, payLoad, types3.NameRemoveValidatorAction) } -//CreateRawModifyValidatorTxCmd ModifyValidator +// CreateRawModifyValidatorTxCmd ModifyValidator func CreateRawModifyValidatorTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "modify", @@ -320,7 +320,7 @@ func modify(cmd *cobra.Command, args []string) { createTx(cmd, payLoad, types3.NameModifyPowerAction) } -//CreateRawSetConsensusTxCmd MsgSetConsensusNeeded +// CreateRawSetConsensusTxCmd MsgSetConsensusNeeded func CreateRawSetConsensusTxCmd() *cobra.Command { cmd := &cobra.Command{ Use: "setconsensus", diff --git a/plugin/dapp/x2ethereum/ebcli/chain33RelayerCmd.go b/plugin/dapp/x2ethereum/ebcli/chain33RelayerCmd.go index 0ed3c31190..1a6368d74e 100644 --- a/plugin/dapp/x2ethereum/ebcli/chain33RelayerCmd.go +++ b/plugin/dapp/x2ethereum/ebcli/chain33RelayerCmd.go @@ -9,7 +9,7 @@ import ( "github.com/spf13/cobra" ) -//Chain33RelayerCmd RelayerCmd command func +// Chain33RelayerCmd RelayerCmd command func func Chain33RelayerCmd() *cobra.Command { cmd := &cobra.Command{ Use: "chain33 ", @@ -26,7 +26,7 @@ func Chain33RelayerCmd() *cobra.Command { return cmd } -//ImportPrivateKeyCmd SetPwdCmd set password +// ImportPrivateKeyCmd SetPwdCmd set password func ImportPrivateKeyCmd() *cobra.Command { cmd := &cobra.Command{ Use: "import_privatekey", @@ -54,7 +54,7 @@ func importPrivatekey(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowValidatorAddrCmd ... +// ShowValidatorAddrCmd ... func ShowValidatorAddrCmd() *cobra.Command { cmd := &cobra.Command{ Use: "show_validator", @@ -71,7 +71,7 @@ func showValidatorAddr(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowTxsHashCmd ... +// ShowTxsHashCmd ... func ShowTxsHashCmd() *cobra.Command { cmd := &cobra.Command{ Use: "show_txhashes", diff --git a/plugin/dapp/x2ethereum/ebcli/ethereumRelayerCmd.go b/plugin/dapp/x2ethereum/ebcli/ethereumRelayerCmd.go index 34fd1528ec..3db79f91a8 100644 --- a/plugin/dapp/x2ethereum/ebcli/ethereumRelayerCmd.go +++ b/plugin/dapp/x2ethereum/ebcli/ethereumRelayerCmd.go @@ -53,7 +53,7 @@ func EthereumRelayerCmd() *cobra.Command { return cmd } -//ImportChain33PrivateKeyCmd ... +// ImportChain33PrivateKeyCmd ... func ImportChain33PrivateKeyCmd() *cobra.Command { cmd := &cobra.Command{ Use: "import_chain33privatekey", @@ -79,7 +79,7 @@ func importChain33Privatekey(cmd *cobra.Command, args []string) { ctx.Run() } -//GenEthPrivateKeyCmd ... +// GenEthPrivateKeyCmd ... func GenEthPrivateKeyCmd() *cobra.Command { cmd := &cobra.Command{ Use: "create_eth_key", @@ -97,7 +97,7 @@ func generateEthereumPrivateKey(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowValidatorsAddrCmd ... +// ShowValidatorsAddrCmd ... func ShowValidatorsAddrCmd() *cobra.Command { cmd := &cobra.Command{ Use: "show_validators", @@ -114,7 +114,7 @@ func showValidatorsAddr(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowChain33TxsHashCmd ... +// ShowChain33TxsHashCmd ... func ShowChain33TxsHashCmd() *cobra.Command { cmd := &cobra.Command{ Use: "show_chain33_tx", @@ -139,7 +139,7 @@ func showChain33Txs(cmd *cobra.Command, args []string) { } } -//ShowEthereumTxsHashCmd ... +// ShowEthereumTxsHashCmd ... func ShowEthereumTxsHashCmd() *cobra.Command { cmd := &cobra.Command{ Use: "show_eth_tx", @@ -164,7 +164,7 @@ func showEthTxs(cmd *cobra.Command, args []string) { } } -//IsValidatorActiveCmd ... +// IsValidatorActiveCmd ... func IsValidatorActiveCmd() *cobra.Command { cmd := &cobra.Command{ Use: "active", @@ -175,13 +175,13 @@ func IsValidatorActiveCmd() *cobra.Command { return cmd } -//IsValidatorActiveFlags ... +// IsValidatorActiveFlags ... func IsValidatorActiveFlags(cmd *cobra.Command) { cmd.Flags().StringP("addr", "a", "", "validator address") _ = cmd.MarkFlagRequired("addr") } -//IsValidatorActive ... +// IsValidatorActive ... func IsValidatorActive(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") addr, _ := cmd.Flags().GetString("addr") @@ -192,7 +192,7 @@ func IsValidatorActive(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowOperatorCmd ... +// ShowOperatorCmd ... func ShowOperatorCmd() *cobra.Command { cmd := &cobra.Command{ Use: "operator", @@ -202,7 +202,7 @@ func ShowOperatorCmd() *cobra.Command { return cmd } -//ShowOperator ... +// ShowOperator ... func ShowOperator(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") var res string @@ -219,7 +219,7 @@ func DeployContrcts2Chain33Cmd() *cobra.Command { return cmd } -//DeployContrctsCmd ... +// DeployContrctsCmd ... func DeployContrcts2EthCmd() *cobra.Command { cmd := &cobra.Command{ Use: "deploy2eth", @@ -229,7 +229,7 @@ func DeployContrcts2EthCmd() *cobra.Command { return cmd } -//DeployContrcts ... +// DeployContrcts ... func DeployContrcts(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") var res rpctypes.Reply @@ -244,7 +244,7 @@ func DeployContrcts2Chain33(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowTxReceiptCmd ... +// ShowTxReceiptCmd ... func ShowTxReceiptCmd() *cobra.Command { cmd := &cobra.Command{ Use: "receipt", @@ -255,13 +255,13 @@ func ShowTxReceiptCmd() *cobra.Command { return cmd } -//ShowTxReceiptFlags ... +// ShowTxReceiptFlags ... func ShowTxReceiptFlags(cmd *cobra.Command) { cmd.Flags().StringP("hash", "s", "", "tx hash") _ = cmd.MarkFlagRequired("hash") } -//ShowTxReceipt ... +// ShowTxReceipt ... func ShowTxReceipt(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") txhash, _ := cmd.Flags().GetString("hash") @@ -271,7 +271,7 @@ func ShowTxReceipt(cmd *cobra.Command, args []string) { ctx.Run() } -//CreateBridgeTokenCmd ... +// CreateBridgeTokenCmd ... func CreateBridgeTokenCmd() *cobra.Command { cmd := &cobra.Command{ Use: "token4chain33", @@ -282,13 +282,13 @@ func CreateBridgeTokenCmd() *cobra.Command { return cmd } -//CreateBridgeTokenFlags ... +// CreateBridgeTokenFlags ... func CreateBridgeTokenFlags(cmd *cobra.Command) { cmd.Flags().StringP("symbol", "s", "", "token symbol") _ = cmd.MarkFlagRequired("symbol") } -//CreateBridgeToken ... +// CreateBridgeToken ... func CreateBridgeToken(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") token, _ := cmd.Flags().GetString("symbol") @@ -298,7 +298,7 @@ func CreateBridgeToken(cmd *cobra.Command, args []string) { ctx.Run() } -//CreateEthereumTokenCmd ... +// CreateEthereumTokenCmd ... func CreateEthereumTokenCmd() *cobra.Command { cmd := &cobra.Command{ Use: "token4erc20", @@ -309,13 +309,13 @@ func CreateEthereumTokenCmd() *cobra.Command { return cmd } -//CreateEthereumTokenFlags ... +// CreateEthereumTokenFlags ... func CreateEthereumTokenFlags(cmd *cobra.Command) { cmd.Flags().StringP("symbol", "s", "", "token symbol") _ = cmd.MarkFlagRequired("symbol") } -//CreateEthereumTokenToken ... +// CreateEthereumTokenToken ... func CreateEthereumTokenToken(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") token, _ := cmd.Flags().GetString("symbol") @@ -325,7 +325,7 @@ func CreateEthereumTokenToken(cmd *cobra.Command, args []string) { ctx.Run() } -//MintErc20Cmd ... +// MintErc20Cmd ... func MintErc20Cmd() *cobra.Command { cmd := &cobra.Command{ Use: "mint", @@ -336,7 +336,7 @@ func MintErc20Cmd() *cobra.Command { return cmd } -//MintErc20Flags ... +// MintErc20Flags ... func MintErc20Flags(cmd *cobra.Command) { cmd.Flags().StringP("token", "t", "", "token address") _ = cmd.MarkFlagRequired("token") @@ -346,7 +346,7 @@ func MintErc20Flags(cmd *cobra.Command) { _ = cmd.MarkFlagRequired("amount") } -//MintErc20 ... +// MintErc20 ... func MintErc20(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") tokenAddr, _ := cmd.Flags().GetString("token") @@ -371,7 +371,7 @@ func MintErc20(cmd *cobra.Command, args []string) { ctx.Run() } -//ApproveCmd ... +// ApproveCmd ... func ApproveCmd() *cobra.Command { cmd := &cobra.Command{ Use: "approve", @@ -382,7 +382,7 @@ func ApproveCmd() *cobra.Command { return cmd } -//ApproveAllowanceFlags ... +// ApproveAllowanceFlags ... func ApproveAllowanceFlags(cmd *cobra.Command) { cmd.Flags().StringP("key", "k", "", "owner private key") _ = cmd.MarkFlagRequired("key") @@ -392,7 +392,7 @@ func ApproveAllowanceFlags(cmd *cobra.Command) { _ = cmd.MarkFlagRequired("amount") } -//ApproveAllowance ... +// ApproveAllowance ... func ApproveAllowance(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") key, _ := cmd.Flags().GetString("key") @@ -417,7 +417,7 @@ func ApproveAllowance(cmd *cobra.Command, args []string) { ctx.Run() } -//BurnCmd ... +// BurnCmd ... func BurnCmd() *cobra.Command { cmd := &cobra.Command{ Use: "burn", @@ -428,7 +428,7 @@ func BurnCmd() *cobra.Command { return cmd } -//BurnAsyncCmd ... +// BurnAsyncCmd ... func BurnAsyncCmd() *cobra.Command { cmd := &cobra.Command{ Use: "burn-async", @@ -439,7 +439,7 @@ func BurnAsyncCmd() *cobra.Command { return cmd } -//BurnFlags ... +// BurnFlags ... func BurnFlags(cmd *cobra.Command) { cmd.Flags().StringP("key", "k", "", "owner private key") _ = cmd.MarkFlagRequired("key") @@ -476,7 +476,7 @@ func Burn(cmd *cobra.Command, args []string) { ctx.Run() } -//BurnAsync ... +// BurnAsync ... func BurnAsync(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") key, _ := cmd.Flags().GetString("key") @@ -501,7 +501,7 @@ func BurnAsync(cmd *cobra.Command, args []string) { ctx.Run() } -//LockSyncCmd ... +// LockSyncCmd ... func LockSyncCmd() *cobra.Command { cmd := &cobra.Command{ Use: "lock", @@ -512,7 +512,7 @@ func LockSyncCmd() *cobra.Command { return cmd } -//LockAsyncCmd ... +// LockAsyncCmd ... func LockAsyncCmd() *cobra.Command { cmd := &cobra.Command{ Use: "lock-async", @@ -523,7 +523,7 @@ func LockAsyncCmd() *cobra.Command { return cmd } -//LockEthErc20AssetFlags ... +// LockEthErc20AssetFlags ... func LockEthErc20AssetFlags(cmd *cobra.Command) { cmd.Flags().StringP("key", "k", "", "owner private key") _ = cmd.MarkFlagRequired("key") @@ -534,7 +534,7 @@ func LockEthErc20AssetFlags(cmd *cobra.Command) { _ = cmd.MarkFlagRequired("receiver") } -//LockEthErc20Asset ... +// LockEthErc20Asset ... func LockEthErc20Asset(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") key, _ := cmd.Flags().GetString("key") @@ -562,7 +562,7 @@ func LockEthErc20Asset(cmd *cobra.Command, args []string) { ctx.Run() } -//LockEthErc20AssetAsync ... +// LockEthErc20AssetAsync ... func LockEthErc20AssetAsync(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") key, _ := cmd.Flags().GetString("key") @@ -590,7 +590,7 @@ func LockEthErc20AssetAsync(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowBridgeBankAddrCmd ... +// ShowBridgeBankAddrCmd ... func ShowBridgeBankAddrCmd() *cobra.Command { cmd := &cobra.Command{ Use: "bridgeBankAddr", @@ -600,7 +600,7 @@ func ShowBridgeBankAddrCmd() *cobra.Command { return cmd } -//ShowBridgeBankAddr ... +// ShowBridgeBankAddr ... func ShowBridgeBankAddr(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") var res ebTypes.ReplyAddr @@ -608,7 +608,7 @@ func ShowBridgeBankAddr(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowBridgeRegistryAddrCmd ... +// ShowBridgeRegistryAddrCmd ... func ShowBridgeRegistryAddrCmd() *cobra.Command { cmd := &cobra.Command{ Use: "bridgeRegistry", @@ -618,7 +618,7 @@ func ShowBridgeRegistryAddrCmd() *cobra.Command { return cmd } -//ShowBridgeRegistryAddr ... +// ShowBridgeRegistryAddr ... func ShowBridgeRegistryAddr(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") var res ebTypes.ReplyAddr @@ -626,7 +626,7 @@ func ShowBridgeRegistryAddr(cmd *cobra.Command, args []string) { ctx.Run() } -//GetBalanceCmd ... +// GetBalanceCmd ... func GetBalanceCmd() *cobra.Command { cmd := &cobra.Command{ Use: "balance", @@ -637,14 +637,14 @@ func GetBalanceCmd() *cobra.Command { return cmd } -//GetBalanceFlags ... +// GetBalanceFlags ... func GetBalanceFlags(cmd *cobra.Command) { cmd.Flags().StringP("owner", "o", "", "owner address") _ = cmd.MarkFlagRequired("owner") cmd.Flags().StringP("tokenAddr", "t", "", "token address, optional, nil for Eth") } -//GetBalance ... +// GetBalance ... func GetBalance(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") owner, _ := cmd.Flags().GetString("owner") @@ -659,7 +659,7 @@ func GetBalance(cmd *cobra.Command, args []string) { ctx.Run() } -//IsProphecyPendingCmd ... +// IsProphecyPendingCmd ... func IsProphecyPendingCmd() *cobra.Command { cmd := &cobra.Command{ Use: "ispending", @@ -670,13 +670,13 @@ func IsProphecyPendingCmd() *cobra.Command { return cmd } -//IsProphecyPendingFlags ... +// IsProphecyPendingFlags ... func IsProphecyPendingFlags(cmd *cobra.Command) { cmd.Flags().StringP("id", "i", "", "claim prophecy id") _ = cmd.MarkFlagRequired("id") } -//IsProphecyPending ... +// IsProphecyPending ... func IsProphecyPending(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") id, _ := cmd.Flags().GetString("id") @@ -687,7 +687,7 @@ func IsProphecyPending(cmd *cobra.Command, args []string) { ctx.Run() } -//TransferTokenCmd ... +// TransferTokenCmd ... func TransferTokenCmd() *cobra.Command { cmd := &cobra.Command{ Use: "transfer", @@ -698,7 +698,7 @@ func TransferTokenCmd() *cobra.Command { return cmd } -//TransferTokenFlags ... +// TransferTokenFlags ... func TransferTokenFlags(cmd *cobra.Command) { cmd.Flags().StringP("token", "t", "", "token address") _ = cmd.MarkFlagRequired("token") @@ -711,7 +711,7 @@ func TransferTokenFlags(cmd *cobra.Command) { } -//TransferToken ... +// TransferToken ... func TransferToken(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") tokenAddr, _ := cmd.Flags().GetString("token") @@ -738,7 +738,7 @@ func TransferToken(cmd *cobra.Command, args []string) { ctx.Run() } -//GetToken2addressCmd ... +// GetToken2addressCmd ... func GetToken2addressCmd() *cobra.Command { cmd := &cobra.Command{ Use: "tokenaddr", @@ -749,14 +749,14 @@ func GetToken2addressCmd() *cobra.Command { return cmd } -//GetToken2addressFlags ... +// GetToken2addressFlags ... func GetToken2addressFlags(cmd *cobra.Command) { cmd.Flags().StringP("token", "t", "", "token symbol") _ = cmd.MarkFlagRequired("token") } -//GetToken2address ... +// GetToken2address ... func GetToken2address(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") tokenSymbol, _ := cmd.Flags().GetString("token") diff --git a/plugin/dapp/x2ethereum/ebcli/main.go b/plugin/dapp/x2ethereum/ebcli/main.go index 10a177c0d6..65c7ce8353 100644 --- a/plugin/dapp/x2ethereum/ebcli/main.go +++ b/plugin/dapp/x2ethereum/ebcli/main.go @@ -57,7 +57,7 @@ func testTLS(RPCAddr string) string { return "https://" + RPCAddr[7:] } -//run : +// run : func run(RPCAddr, NodeAddr string) { //test tls is enable RPCAddr = testTLS(RPCAddr) diff --git a/plugin/dapp/x2ethereum/ebcli/statics.go b/plugin/dapp/x2ethereum/ebcli/statics.go index d9669be03f..e651fa2f2e 100644 --- a/plugin/dapp/x2ethereum/ebcli/statics.go +++ b/plugin/dapp/x2ethereum/ebcli/statics.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" ) -//StaticsCmd ... +// StaticsCmd ... func StaticsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "statics", @@ -22,7 +22,7 @@ func StaticsCmd() *cobra.Command { return cmd } -//ShowLockStaticsCmd ... +// ShowLockStaticsCmd ... func ShowLockStaticsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "lock", @@ -33,12 +33,12 @@ func ShowLockStaticsCmd() *cobra.Command { return cmd } -//ShowLockStaticsFlags ... +// ShowLockStaticsFlags ... func ShowLockStaticsFlags(cmd *cobra.Command) { cmd.Flags().StringP("token", "t", "", "token address, optional, nil for ETH") } -//ShowLockStatics ... +// ShowLockStatics ... func ShowLockStatics(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") tokenAddr, _ := cmd.Flags().GetString("token") @@ -51,7 +51,7 @@ func ShowLockStatics(cmd *cobra.Command, args []string) { ctx.Run() } -//ShowDepositStaticsCmd ... +// ShowDepositStaticsCmd ... func ShowDepositStaticsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "deposit", @@ -62,13 +62,13 @@ func ShowDepositStaticsCmd() *cobra.Command { return cmd } -//ShowDepositStaticsFlags ... +// ShowDepositStaticsFlags ... func ShowDepositStaticsFlags(cmd *cobra.Command) { cmd.Flags().StringP("token", "t", "", "token address") _ = cmd.MarkFlagRequired("token") } -//ShowDepositStatics ... +// ShowDepositStatics ... func ShowDepositStatics(cmd *cobra.Command, args []string) { rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") tokenAddr, _ := cmd.Flags().GetString("token") diff --git a/plugin/dapp/x2ethereum/ebrelayer/ethcontract/test/setup/setupTestEnv.go b/plugin/dapp/x2ethereum/ebrelayer/ethcontract/test/setup/setupTestEnv.go index 23b5307537..bb6f9b9894 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/ethcontract/test/setup/setupTestEnv.go +++ b/plugin/dapp/x2ethereum/ebrelayer/ethcontract/test/setup/setupTestEnv.go @@ -16,7 +16,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" ) -//PrepareTestEnv ... +// PrepareTestEnv ... func PrepareTestEnv() (*ethinterface.SimExtend, *ethtxs.DeployPara) { genesiskey, _ := crypto.GenerateKey() alloc := make(core.GenesisAlloc) @@ -58,7 +58,7 @@ func PrepareTestEnv() (*ethinterface.SimExtend, *ethtxs.DeployPara) { return sim, para } -//PrepareTestEnvironment ... +// PrepareTestEnvironment ... func PrepareTestEnvironment(deployerPrivateKey string, ethValidatorAddrKeys []string) (bind.ContractBackend, *ethtxs.DeployPara) { genesiskey, _ := crypto.HexToECDSA(deployerPrivateKey) alloc := make(core.GenesisAlloc) @@ -101,7 +101,7 @@ func PrepareTestEnvironment(deployerPrivateKey string, ethValidatorAddrKeys []st return sim, para } -//DeployContracts ... +// DeployContracts ... func DeployContracts() (*ethtxs.DeployPara, *ethinterface.SimExtend, *ethtxs.X2EthContracts, *ethtxs.X2EthDeployInfo, error) { ctx := context.Background() sim, para := PrepareTestEnv() diff --git a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/abi.go b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/abi.go index 384b612ff8..bfda8c2d0f 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/abi.go +++ b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/abi.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" ) -//const +// const const ( BridgeBankABI = "BridgeBankABI" Chain33BankABI = "Chain33BankABI" @@ -15,7 +15,7 @@ const ( EthereumBankABI = "EthereumBankABI" ) -//LoadABI ... +// LoadABI ... func LoadABI(contractName string) abi.ABI { var abiJSON string switch contractName { diff --git a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/auxiliary.go b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/auxiliary.go index 7b606d95bd..de776eda76 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/auxiliary.go +++ b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/auxiliary.go @@ -15,7 +15,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" ) -//NewProphecyClaimPara ... +// NewProphecyClaimPara ... type NewProphecyClaimPara struct { ClaimType uint8 Chain33Sender []byte @@ -26,7 +26,7 @@ type NewProphecyClaimPara struct { Txhash []byte } -//CreateBridgeToken ... +// CreateBridgeToken ... func CreateBridgeToken(symbol string, client ethinterface.EthClientSpec, para *OperatorInfo, x2EthDeployInfo *X2EthDeployInfo, x2EthContracts *X2EthContracts) (string, error) { if nil == para { return "", errors.New("no operator private key configured") @@ -104,7 +104,7 @@ func CreateBridgeToken(symbol string, client ethinterface.EthClientSpec, para *O return logEvent.Token.String(), nil } -//CreateERC20Token ... +// CreateERC20Token ... func CreateERC20Token(symbol string, client ethinterface.EthClientSpec, para *OperatorInfo) (string, error) { if nil == para { return "", errors.New("no operator private key configured") @@ -139,7 +139,7 @@ func CreateERC20Token(symbol string, client ethinterface.EthClientSpec, para *Op return tokenAddr.String(), nil } -//MintERC20Token ... +// MintERC20Token ... func MintERC20Token(tokenAddr, ownerAddr string, amount *big.Int, client ethinterface.EthClientSpec, para *OperatorInfo) (string, error) { if nil == para { return "", errors.New("no operator private key configured") @@ -178,7 +178,7 @@ func MintERC20Token(tokenAddr, ownerAddr string, amount *big.Int, client ethinte return tx.Hash().String(), nil } -//ApproveAllowance ... +// ApproveAllowance ... func ApproveAllowance(ownerPrivateKeyStr, tokenAddr string, bridgeBank common.Address, amount *big.Int, client ethinterface.EthClientSpec) (string, error) { ownerPrivateKey, err := crypto.ToECDSA(common.FromHex(ownerPrivateKeyStr)) if nil != err { @@ -219,7 +219,7 @@ func ApproveAllowance(ownerPrivateKeyStr, tokenAddr string, bridgeBank common.Ad return tx.Hash().String(), nil } -//Burn ... +// Burn ... func Burn(ownerPrivateKeyStr, tokenAddrstr, chain33Receiver string, bridgeBank common.Address, amount *big.Int, bridgeBankIns *generated.BridgeBank, client ethinterface.EthClientSpec) (string, error) { ownerPrivateKey, err := crypto.ToECDSA(common.FromHex(ownerPrivateKeyStr)) if nil != err { @@ -278,7 +278,7 @@ func Burn(ownerPrivateKeyStr, tokenAddrstr, chain33Receiver string, bridgeBank c return tx.Hash().String(), nil } -//BurnAsync ... +// BurnAsync ... func BurnAsync(ownerPrivateKeyStr, tokenAddrstr, chain33Receiver string, amount *big.Int, bridgeBankIns *generated.BridgeBank, client ethinterface.EthClientSpec) (string, error) { ownerPrivateKey, err := crypto.ToECDSA(common.FromHex(ownerPrivateKeyStr)) if nil != err { @@ -309,7 +309,7 @@ func BurnAsync(ownerPrivateKeyStr, tokenAddrstr, chain33Receiver string, amount return tx.Hash().String(), nil } -//TransferToken ... +// TransferToken ... func TransferToken(tokenAddr, fromPrivateKeyStr, toAddr string, amount *big.Int, client ethinterface.EthClientSpec) (string, error) { tokenInstance, err := generated.NewBridgeToken(common.HexToAddress(tokenAddr), client) if nil != err { @@ -349,7 +349,7 @@ func TransferToken(tokenAddr, fromPrivateKeyStr, toAddr string, amount *big.Int, return tx.Hash().String(), nil } -//LockEthErc20Asset ... +// LockEthErc20Asset ... func LockEthErc20Asset(ownerPrivateKeyStr, tokenAddrStr, chain33Receiver string, amount *big.Int, client ethinterface.EthClientSpec, bridgeBank *generated.BridgeBank, bridgeBankAddr common.Address) (string, error) { var prepareDone bool txslog.Info("LockEthErc20Asset", "ownerPrivateKeyStr", ownerPrivateKeyStr, "tokenAddrStr", tokenAddrStr, "chain33Receiver", chain33Receiver, "amount", amount.String()) @@ -422,7 +422,7 @@ func LockEthErc20Asset(ownerPrivateKeyStr, tokenAddrStr, chain33Receiver string, return tx.Hash().String(), nil } -//LockEthErc20AssetAsync ... +// LockEthErc20AssetAsync ... func LockEthErc20AssetAsync(ownerPrivateKeyStr, tokenAddrStr, chain33Receiver string, amount *big.Int, client ethinterface.EthClientSpec, bridgeBank *generated.BridgeBank) (string, error) { txslog.Info("LockEthErc20AssetAsync", "ownerPrivateKeyStr", ownerPrivateKeyStr, "tokenAddrStr", tokenAddrStr, "chain33Receiver", chain33Receiver, "amount", amount.String()) ownerPrivateKey, err := crypto.ToECDSA(common.FromHex(ownerPrivateKeyStr)) diff --git a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/deploy.go b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/deploy.go index 045165ef7c..e7d4368e37 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/deploy.go +++ b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/deploy.go @@ -19,13 +19,13 @@ var ( deployLog = log15.New("contract deployer", "deployer") ) -//DeployResult ... +// DeployResult ... type DeployResult struct { Address common.Address TxHash string } -//X2EthContracts ... +// X2EthContracts ... type X2EthContracts struct { BridgeRegistry *generated.BridgeRegistry BridgeBank *generated.BridgeBank @@ -34,7 +34,7 @@ type X2EthContracts struct { Oracle *generated.Oracle } -//X2EthDeployInfo ... +// X2EthDeployInfo ... type X2EthDeployInfo struct { BridgeRegistry *DeployResult BridgeBank *DeployResult @@ -43,7 +43,7 @@ type X2EthDeployInfo struct { Oracle *DeployResult } -//DeployPara ... +// DeployPara ... type DeployPara struct { DeployPrivateKey *ecdsa.PrivateKey Deployer common.Address @@ -53,13 +53,13 @@ type DeployPara struct { InitPowers []*big.Int } -//OperatorInfo ... +// OperatorInfo ... type OperatorInfo struct { PrivateKey *ecdsa.PrivateKey Address common.Address } -//DeployValset : 部署Valset +// DeployValset : 部署Valset func DeployValset(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer common.Address, operator common.Address, initValidators []common.Address, initPowers []*big.Int) (*generated.Valset, *DeployResult, error) { auth, err := PrepareAuth(client, privateKey, deployer) if nil != err { @@ -80,7 +80,7 @@ func DeployValset(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKe return valset, deployResult, nil } -//DeployChain33Bridge : 部署Chain33Bridge +// DeployChain33Bridge : 部署Chain33Bridge func DeployChain33Bridge(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer common.Address, operator, valset common.Address) (*generated.Chain33Bridge, *DeployResult, error) { auth, err := PrepareAuth(client, privateKey, deployer) if nil != err { @@ -100,7 +100,7 @@ func DeployChain33Bridge(client ethinterface.EthClientSpec, privateKey *ecdsa.Pr return chain33Bridge, deployResult, nil } -//DeployOracle : 部署Oracle +// DeployOracle : 部署Oracle func DeployOracle(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer, operator, valset, chain33Bridge common.Address) (*generated.Oracle, *DeployResult, error) { auth, err := PrepareAuth(client, privateKey, deployer) if nil != err { @@ -120,7 +120,7 @@ func DeployOracle(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKe return oracle, deployResult, nil } -//DeployBridgeBank : 部署BridgeBank +// DeployBridgeBank : 部署BridgeBank func DeployBridgeBank(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer, operator, oracle, chain33Bridge common.Address) (*generated.BridgeBank, *DeployResult, error) { auth, err := PrepareAuth(client, privateKey, deployer) if nil != err { @@ -140,7 +140,7 @@ func DeployBridgeBank(client ethinterface.EthClientSpec, privateKey *ecdsa.Priva return bridgeBank, deployResult, nil } -//DeployBridgeRegistry : 部署BridgeRegistry +// DeployBridgeRegistry : 部署BridgeRegistry func DeployBridgeRegistry(client ethinterface.EthClientSpec, privateKey *ecdsa.PrivateKey, deployer, chain33BridgeAddr, bridgeBankAddr, oracleAddr, valsetAddr common.Address) (*generated.BridgeRegistry, *DeployResult, error) { auth, err := PrepareAuth(client, privateKey, deployer) if nil != err { @@ -160,7 +160,7 @@ func DeployBridgeRegistry(client ethinterface.EthClientSpec, privateKey *ecdsa.P return bridgeRegistry, deployResult, nil } -//DeployAndInit ... +// DeployAndInit ... func DeployAndInit(client ethinterface.EthClientSpec, para *DeployPara) (*X2EthContracts, *X2EthDeployInfo, error) { x2EthContracts := &X2EthContracts{} deployInfo := &X2EthDeployInfo{} diff --git a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/parser.go b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/parser.go index ca85c8b15d..2ba0cd396d 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/parser.go +++ b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/parser.go @@ -55,7 +55,7 @@ func LogLockToEthBridgeClaim(event *events.LockEvent, ethereumChainID int64, bri return witnessClaim, nil } -//LogBurnToEthBridgeClaim ... +// LogBurnToEthBridgeClaim ... func LogBurnToEthBridgeClaim(event *events.BurnEvent, ethereumChainID int64, bridgeBrankAddr string, decimal int64) (*ebrelayerTypes.EthBridgeClaim, error) { recipient := event.Chain33Receiver if 0 == len(recipient) { diff --git a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/queryFromEth.go b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/queryFromEth.go index 8c2cc70c74..7fc1b2e792 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/queryFromEth.go +++ b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/queryFromEth.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common" ) -//GetOperator ... +// GetOperator ... func GetOperator(client ethinterface.EthClientSpec, sender, bridgeBank common.Address) (common.Address, error) { header, err := client.HeaderByNumber(context.Background(), nil) if err != nil { @@ -36,7 +36,7 @@ func GetOperator(client ethinterface.EthClientSpec, sender, bridgeBank common.Ad return bridgeBankInstance.Operator(&auth) } -//IsActiveValidator ... +// IsActiveValidator ... func IsActiveValidator(validator common.Address, valset *generated.Valset) (bool, error) { opts := &bind.CallOpts{ Pending: true, @@ -54,7 +54,7 @@ func IsActiveValidator(validator common.Address, valset *generated.Valset) (bool return isActiveValidator, nil } -//IsProphecyPending ... +// IsProphecyPending ... func IsProphecyPending(claimID [32]byte, validator common.Address, chain33Bridge *generated.Chain33Bridge) (bool, error) { opts := &bind.CallOpts{ Pending: true, @@ -71,7 +71,7 @@ func IsProphecyPending(claimID [32]byte, validator common.Address, chain33Bridge return active, nil } -//GetBalance ... +// GetBalance ... func GetBalance(client ethinterface.EthClientSpec, tokenAddr, owner string) (string, error) { //查询ERC20余额 if tokenAddr != "" { @@ -100,7 +100,7 @@ func GetBalance(client ethinterface.EthClientSpec, tokenAddr, owner string) (str return balance.String(), nil } -//GetLockedFunds ... +// GetLockedFunds ... func GetLockedFunds(bridgeBank *generated.BridgeBank, tokenAddrStr string) (string, error) { var tokenAddr common.Address if tokenAddrStr != "" { @@ -118,7 +118,7 @@ func GetLockedFunds(bridgeBank *generated.BridgeBank, tokenAddrStr string) (stri return balance.String(), nil } -//GetDepositFunds ... +// GetDepositFunds ... func GetDepositFunds(client bind.ContractBackend, tokenAddrStr string) (string, error) { if tokenAddrStr == "" { return "", errors.New("nil token address") @@ -142,7 +142,7 @@ func GetDepositFunds(client bind.ContractBackend, tokenAddrStr string) (string, return supply.String(), nil } -//GetToken2address ... +// GetToken2address ... func GetToken2address(bridgeBank *generated.BridgeBank, tokenSymbol string) (string, error) { opts := &bind.CallOpts{ Pending: true, diff --git a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/recover.go b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/recover.go index f9ff9220cf..e5413c0f19 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/recover.go +++ b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/recover.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/common" ) -//RecoverContractHandler ... +// RecoverContractHandler ... func RecoverContractHandler(client ethinterface.EthClientSpec, sender, registry common.Address) (*X2EthContracts, *X2EthDeployInfo, error) { bridgeBankAddr, err := GetAddressFromBridgeRegistry(client, sender, registry, BridgeBank) if nil != err { @@ -66,7 +66,7 @@ func RecoverContractHandler(client ethinterface.EthClientSpec, sender, registry return x2EthContracts, x2EthDeployInfo, nil } -//RecoverOracleInstance ... +// RecoverOracleInstance ... func RecoverOracleInstance(client ethinterface.EthClientSpec, sender, registry common.Address) (*generated.Oracle, error) { oracleAddr, err := GetAddressFromBridgeRegistry(client, sender, registry, Oracle) if nil != err { diff --git a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/relayToChain33.go b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/relayToChain33.go index 1dd446390f..044ad20651 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/relayToChain33.go +++ b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/relayToChain33.go @@ -19,7 +19,8 @@ import ( ) // RelayLockToChain33 : RelayLockToChain33 applies validator's signature to an EthBridgeClaim message -// containing information about an event on the Ethereum blockchain before relaying to the Bridge +// +// containing information about an event on the Ethereum blockchain before relaying to the Bridge func RelayLockToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes.EthBridgeClaim, rpcURL string) (string, error) { var res string @@ -76,7 +77,7 @@ func RelayLockToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes. return txhash, err } -//RelayBurnToChain33 ... +// RelayBurnToChain33 ... func RelayBurnToChain33(privateKey chain33Crypto.PrivKey, claim *ebrelayerTypes.EthBridgeClaim, rpcURL string) (string, error) { var res string diff --git a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/relayToEthereum.go b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/relayToEthereum.go index 0546cf576e..c8845237df 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/relayToEthereum.go +++ b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/relayToEthereum.go @@ -17,7 +17,7 @@ var ( txslog = log15.New("ethereum relayer", "ethtxs") ) -//const ... +// const ... const ( // GasLimit : the gas limit in Gwei used for transactions sent with TransactOpts GasLimit = uint64(100 * 10000) diff --git a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/types.go b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/types.go index 8081334f37..002a7d7194 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/ethtxs/types.go +++ b/plugin/dapp/x2ethereum/ebrelayer/ethtxs/types.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" ) -//const ... +// const ... const ( X2Eth = "x2ethereum" BurnAction = "Chain33ToEthBurn" diff --git a/plugin/dapp/x2ethereum/ebrelayer/events/ethereumEvent.go b/plugin/dapp/x2ethereum/ebrelayer/events/ethereumEvent.go index 8197fbaa3e..8fa4e48319 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/events/ethereumEvent.go +++ b/plugin/dapp/x2ethereum/ebrelayer/events/ethereumEvent.go @@ -45,7 +45,7 @@ type NewProphecyClaimEvent struct { Amount *big.Int } -//LogNewBridgeToken ... +// LogNewBridgeToken ... type LogNewBridgeToken struct { Token common.Address Symbol string @@ -68,7 +68,7 @@ func UnpackLogLock(contractAbi abi.ABI, eventName string, eventData []byte) (loc return event, nil } -//UnpackLogBurn ... +// UnpackLogBurn ... func UnpackLogBurn(contractAbi abi.ABI, eventName string, eventData []byte) (burnEvent *BurnEvent, err error) { event := &BurnEvent{} // Parse the event's attributes as Ethereum network variables diff --git a/plugin/dapp/x2ethereum/ebrelayer/events/events.go b/plugin/dapp/x2ethereum/ebrelayer/events/events.go index 4e74bd4815..fd6529ad85 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/events/events.go +++ b/plugin/dapp/x2ethereum/ebrelayer/events/events.go @@ -24,7 +24,7 @@ const ( LogNewProphecyClaim ) -//const +// const const ( ClaimTypeBurn = uint8(1) ClaimTypeLock = uint8(2) diff --git a/plugin/dapp/x2ethereum/ebrelayer/main.go b/plugin/dapp/x2ethereum/ebrelayer/main.go index 67556793c7..fd62f37375 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/main.go +++ b/plugin/dapp/x2ethereum/ebrelayer/main.go @@ -120,12 +120,12 @@ func initCfg(path string) *relayerTypes.RelayerConfig { return &cfg } -//IsIPWhiteListEmpty ... +// IsIPWhiteListEmpty ... func IsIPWhiteListEmpty() bool { return len(IPWhiteListMap) == 0 } -//IsInIPWhitelist 判断ipAddr是否在ip地址白名单中 +// IsInIPWhitelist 判断ipAddr是否在ip地址白名单中 func IsInIPWhitelist(ipAddrPort string) bool { ipAddr, _, err := net.SplitHostPort(ipAddrPort) if err != nil { @@ -141,12 +141,12 @@ func IsInIPWhitelist(ipAddrPort string) bool { return false } -//RPCServer ... +// RPCServer ... type RPCServer struct { *rpc.Server } -//ServeHTTP ... +// ServeHTTP ... func (r *RPCServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { mainlog.Info("ServeHTTP", "request address", req.RemoteAddr) if !IsIPWhiteListEmpty() { @@ -159,24 +159,24 @@ func (r *RPCServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { r.Server.ServeHTTP(w, req) } -//HandleHTTP ... +// HandleHTTP ... func (r *RPCServer) HandleHTTP(rpcPath, debugPath string) { http.Handle(rpcPath, r) } -//HTTPConn ... +// HTTPConn ... type HTTPConn struct { in io.Reader out io.Writer } -//Read ... +// Read ... func (c *HTTPConn) Read(p []byte) (n int, err error) { return c.in.Read(p) } -//Write ... +// Write ... func (c *HTTPConn) Write(d []byte) (n int, err error) { return c.out.Write(d) } -//Close ... +// Close ... func (c *HTTPConn) Close() error { return nil } func startRPCServer(address string, api interface{}) { diff --git a/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/account.go b/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/account.go index 019c627f1b..7b33539613 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/account.go +++ b/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/account.go @@ -15,7 +15,7 @@ var ( start = int(1) ) -//GetAccount ... +// GetAccount ... func (chain33Relayer *Relayer4Chain33) GetAccount(passphrase string) (privateKey, addr string, err error) { accountInfo, err := chain33Relayer.db.Get(chain33AccountKey) if nil != err { @@ -31,7 +31,7 @@ func (chain33Relayer *Relayer4Chain33) GetAccount(passphrase string) (privateKey return } -//GetAccountAddr ... +// GetAccountAddr ... func (chain33Relayer *Relayer4Chain33) GetAccountAddr() (addr string, err error) { accountInfo, err := chain33Relayer.db.Get(chain33AccountKey) if nil != err { @@ -47,7 +47,7 @@ func (chain33Relayer *Relayer4Chain33) GetAccountAddr() (addr string, err error) return } -//ImportPrivateKey ... +// ImportPrivateKey ... func (chain33Relayer *Relayer4Chain33) ImportPrivateKey(passphrase, privateKeyStr string) (addr string, err error) { privateKeySlice, err := chain33Common.FromHex(privateKeyStr) if nil != err { @@ -75,7 +75,7 @@ func (chain33Relayer *Relayer4Chain33) ImportPrivateKey(passphrase, privateKeySt return } -//StoreAccountWithNewPassphase ... +// StoreAccountWithNewPassphase ... func (chain33Relayer *Relayer4Chain33) StoreAccountWithNewPassphase(newPassphrase, oldPassphrase string) error { accountInfo, err := chain33Relayer.db.Get(chain33AccountKey) if nil != err { @@ -93,7 +93,7 @@ func (chain33Relayer *Relayer4Chain33) StoreAccountWithNewPassphase(newPassphras return chain33Relayer.db.SetSync(chain33AccountKey, encodedInfo) } -//RestorePrivateKeys ... +// RestorePrivateKeys ... func (chain33Relayer *Relayer4Chain33) RestorePrivateKeys(passphrase string) error { accountInfo, err := chain33Relayer.db.Get(chain33AccountKey) if nil != err { diff --git a/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/chain33.go b/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/chain33.go index 4fc7020cf6..8edb0ef7fd 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/chain33.go +++ b/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/chain33.go @@ -29,7 +29,7 @@ import ( var relayerLog = log.New("module", "chain33_relayer") -//Relayer4Chain33 ... +// Relayer4Chain33 ... type Relayer4Chain33 struct { syncTxReceipts *syncTx.TxReceipts ethClient ethinterface.EthClientSpec @@ -83,7 +83,7 @@ func StartChain33Relayer(ctx context.Context, syncTxConfig *ebTypes.SyncTxConfig return chian33Relayer } -//QueryTxhashRelay2Eth ... +// QueryTxhashRelay2Eth ... func (chain33Relayer *Relayer4Chain33) QueryTxhashRelay2Eth() ebTypes.Txhashes { txhashs := utils.QueryTxhashes([]byte(chain33ToEthBurnLockTxHashPrefix), chain33Relayer.db) return ebTypes.Txhashes{Txhash: txhashs} diff --git a/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/store.go b/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/store.go index 4b2d3af332..149ad6d95d 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/store.go +++ b/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/store.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/common" ) -//key ... +// key ... var ( lastSyncHeightPrefix = []byte("lastSyncHeight:") chain33ToEthBurnLockTxHashPrefix = "chain33ToEthBurnLockTxHash" @@ -72,7 +72,7 @@ func (chain33Relayer *Relayer4Chain33) getStatusCheckedIndex() int64 { return index } -//获取上次同步到app的高度 +// 获取上次同步到app的高度 func (chain33Relayer *Relayer4Chain33) loadLastSyncHeight() int64 { height, err := utils.LoadInt64FromDB(lastSyncHeightPrefix, chain33Relayer.db) if nil != err && err != types.ErrHeightNotExist { diff --git a/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/transceiver/sync/proc.go b/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/transceiver/sync/proc.go index 39d26dda15..73bf54138e 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/transceiver/sync/proc.go +++ b/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/transceiver/sync/proc.go @@ -43,7 +43,7 @@ func pushTxReceipts(txReceipts *types.TxReceipts4Subscribe) error { return err } -//TxReceipts ... +// TxReceipts ... type TxReceipts struct { db dbm.DB seqNum int64 //当前同步的序列号 @@ -51,7 +51,7 @@ type TxReceipts struct { quit chan struct{} } -//NewSyncTxReceipts ... +// NewSyncTxReceipts ... func NewSyncTxReceipts(db dbm.DB) *TxReceipts { sync := &TxReceipts{ db: db, @@ -64,7 +64,7 @@ func NewSyncTxReceipts(db dbm.DB) *TxReceipts { return sync } -//此处添加一个高度为0的空块,只是为了查找下一个比较方便,并不需要使用其信息 +// 此处添加一个高度为0的空块,只是为了查找下一个比较方便,并不需要使用其信息 func (syncTx *TxReceipts) initSyncReceiptDataBase() { txblock0, _ := syncTx.GetTxReceipts(0) if nil != txblock0 { @@ -76,7 +76,7 @@ func (syncTx *TxReceipts) initSyncReceiptDataBase() { syncTx.setTxReceiptsPerBlock(txsPerBlock) } -//Stop ... +// Stop ... func (syncTx *TxReceipts) Stop() { close(syncTx.quit) } @@ -144,7 +144,7 @@ func (syncTx *TxReceipts) loadBlockLastSequence() (int64, error) { return utils.LoadInt64FromDB(lastSequences, syncTx.db) } -//LoadLastBlockHeight ... +// LoadLastBlockHeight ... func (syncTx *TxReceipts) LoadLastBlockHeight() (int64, error) { return utils.LoadInt64FromDB(syncLastHeight, syncTx.db) } @@ -174,7 +174,7 @@ func (syncTx *TxReceipts) setTxReceiptsPerBlock(txReceipts *types.TxReceipts4Sub } } -//GetTxReceipts ... +// GetTxReceipts ... func (syncTx *TxReceipts) GetTxReceipts(height int64) (*types.TxReceipts4SubscribePerBlk, error) { key := txReceiptsKey4Height(height) value, err := syncTx.db.Get(key) @@ -189,7 +189,7 @@ func (syncTx *TxReceipts) GetTxReceipts(height int64) (*types.TxReceipts4Subscri return detail, nil } -//GetNextValidTxReceipts ... +// GetNextValidTxReceipts ... func (syncTx *TxReceipts) GetNextValidTxReceipts(height int64) (*types.TxReceipts4SubscribePerBlk, error) { key := txReceiptsKey4Height(height) helper := dbm.NewListHelper(syncTx.db) diff --git a/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/transceiver/sync/pubilc_sync.go b/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/transceiver/sync/pubilc_sync.go index 73ecc94427..fcf119502e 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/transceiver/sync/pubilc_sync.go +++ b/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/transceiver/sync/pubilc_sync.go @@ -1,6 +1,6 @@ package sync -//HandleRequest ... +// HandleRequest ... func HandleRequest(body []byte) error { return handleRequest(body) } diff --git a/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/transceiver/sync/sync_tx_receipts.go b/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/transceiver/sync/sync_tx_receipts.go index 6b957ef3d3..a7e751e358 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/transceiver/sync/sync_tx_receipts.go +++ b/plugin/dapp/x2ethereum/ebrelayer/relayer/chain33/transceiver/sync/sync_tx_receipts.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//Package sync ... +// Package sync ... package sync import ( @@ -27,7 +27,7 @@ var ( syncTxReceipts *TxReceipts ) -//StartSyncTxReceipt ... +// StartSyncTxReceipt ... func StartSyncTxReceipt(cfg *relayerTypes.SyncTxReceiptConfig, db dbm.DB) *TxReceipts { log.Debug("StartSyncTxReceipt, load config", "para:", cfg) log.Debug("TxReceipts started ") @@ -123,9 +123,9 @@ func checkClient(addr string, expectClient string) bool { return addr == expectClient } -//向chain33节点的注册推送交易回执,AddSubscribeTxReceipt具有2种功能: -//首次注册功能,如果没有进行过注册,则进行首次注册 -//如果已经注册,则继续推送 +// 向chain33节点的注册推送交易回执,AddSubscribeTxReceipt具有2种功能: +// 首次注册功能,如果没有进行过注册,则进行首次注册 +// 如果已经注册,则继续推送 func bindOrResumePush(cfg *relayerTypes.SyncTxReceiptConfig) { contract := make(map[string]bool) contract["x2ethereum"] = true diff --git a/plugin/dapp/x2ethereum/ebrelayer/relayer/ethereum/account.go b/plugin/dapp/x2ethereum/ebrelayer/relayer/ethereum/account.go index c12c342619..af524ffadb 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/relayer/ethereum/account.go +++ b/plugin/dapp/x2ethereum/ebrelayer/relayer/ethereum/account.go @@ -27,7 +27,7 @@ var ( start = int(1) ) -//Key ... +// Key ... type Key struct { ID uuid.UUID // Version 4 "random" for unique id not derived from key data // to simplify lookups we also store the address @@ -37,7 +37,7 @@ type Key struct { PrivateKey *ecdsa.PrivateKey } -//NewAccount ... +// NewAccount ... func (ethRelayer *Relayer4Ethereum) NewAccount(passphrase string) (privateKeystr, addr string, err error) { _, privateKeystr, addr, err = newKeyAndStore(ethRelayer.db, crand.Reader, passphrase) if err != nil { @@ -46,7 +46,7 @@ func (ethRelayer *Relayer4Ethereum) NewAccount(passphrase string) (privateKeystr return } -//GetAccount ... +// GetAccount ... func (ethRelayer *Relayer4Ethereum) GetAccount(passphrase string) (privateKey, addr string, err error) { accountInfo, err := ethRelayer.db.Get(chain33AccountKey) if nil != err { @@ -62,7 +62,7 @@ func (ethRelayer *Relayer4Ethereum) GetAccount(passphrase string) (privateKey, a return } -//GetValidatorAddr ... +// GetValidatorAddr ... func (ethRelayer *Relayer4Ethereum) GetValidatorAddr() (validators x2ethTypes.ValidatorAddr4EthRelayer, err error) { var chain33AccountAddr string accountInfo, err := ethRelayer.db.Get(chain33AccountKey) @@ -83,7 +83,7 @@ func (ethRelayer *Relayer4Ethereum) GetValidatorAddr() (validators x2ethTypes.Va return } -//RestorePrivateKeys ... +// RestorePrivateKeys ... func (ethRelayer *Relayer4Ethereum) RestorePrivateKeys(passPhase string) (err error) { accountInfo, err := ethRelayer.db.Get(chain33AccountKey) if nil == err { @@ -112,7 +112,7 @@ func (ethRelayer *Relayer4Ethereum) RestorePrivateKeys(passPhase string) (err er return nil } -//StoreAccountWithNewPassphase ... +// StoreAccountWithNewPassphase ... func (ethRelayer *Relayer4Ethereum) StoreAccountWithNewPassphase(newPassphrase, oldPassphrase string) error { accountInfo, err := ethRelayer.db.Get(chain33AccountKey) if nil != err { @@ -130,7 +130,7 @@ func (ethRelayer *Relayer4Ethereum) StoreAccountWithNewPassphase(newPassphrase, return ethRelayer.db.SetSync(chain33AccountKey, encodedInfo) } -//ImportChain33PrivateKey ... +// ImportChain33PrivateKey ... func (ethRelayer *Relayer4Ethereum) ImportChain33PrivateKey(passphrase, privateKeyStr string) error { var driver secp256k1.Driver privateKeySli, err := chain33Common.FromHex(privateKeyStr) @@ -160,7 +160,7 @@ func (ethRelayer *Relayer4Ethereum) ImportChain33PrivateKey(passphrase, privateK return ethRelayer.db.SetSync(chain33AccountKey, encodedInfo) } -//checksum: first four bytes of double-SHA256. +// checksum: first four bytes of double-SHA256. func checksum(input []byte) (cksum [4]byte) { h := sha256.New() _, err := h.Write(input) diff --git a/plugin/dapp/x2ethereum/ebrelayer/relayer/ethereum/ethereum.go b/plugin/dapp/x2ethereum/ebrelayer/relayer/ethereum/ethereum.go index 435c76e1be..d6bdeaeb7b 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/relayer/ethereum/ethereum.go +++ b/plugin/dapp/x2ethereum/ebrelayer/relayer/ethereum/ethereum.go @@ -37,7 +37,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" ) -//Relayer4Ethereum ... +// Relayer4Ethereum ... type Relayer4Ethereum struct { provider string clientChainID *big.Int @@ -70,12 +70,12 @@ var ( relayerLog = log.New("module", "ethereum_relayer") ) -//const ... +// const ... const ( DefaultBlockPeriod = 5000 ) -//StartEthereumRelayer /// +// StartEthereumRelayer /// func StartEthereumRelayer(rpcURL2Chain33 string, db dbm.DB, provider, registryAddress string, deploy *ebTypes.Deploy, degree, blockInterval int32) *Relayer4Ethereum { if 0 == blockInterval { blockInterval = DefaultBlockPeriod @@ -143,7 +143,7 @@ func (ethRelayer *Relayer4Ethereum) recoverDeployPara() (err error) { return nil } -//DeployContrcts 部署以太坊合约 +// DeployContrcts 部署以太坊合约 func (ethRelayer *Relayer4Ethereum) DeployContrcts() (bridgeRegistry string, err error) { bridgeRegistry = "" if nil == ethRelayer.deployInfo { @@ -212,12 +212,12 @@ func (ethRelayer *Relayer4Ethereum) DeployContrcts() (bridgeRegistry string, err return bridgeRegistry, nil } -//GetBalance :获取某一个币种的余额 +// GetBalance :获取某一个币种的余额 func (ethRelayer *Relayer4Ethereum) GetBalance(tokenAddr, owner string) (string, error) { return ethtxs.GetBalance(ethRelayer.clientSpec, tokenAddr, owner) } -//ShowBridgeBankAddr ... +// ShowBridgeBankAddr ... func (ethRelayer *Relayer4Ethereum) ShowBridgeBankAddr() (string, error) { if nil == ethRelayer.x2EthDeployInfo { return "", errors.New("the relayer is not started yes") @@ -226,7 +226,7 @@ func (ethRelayer *Relayer4Ethereum) ShowBridgeBankAddr() (string, error) { return ethRelayer.x2EthDeployInfo.BridgeBank.Address.String(), nil } -//ShowBridgeRegistryAddr ... +// ShowBridgeRegistryAddr ... func (ethRelayer *Relayer4Ethereum) ShowBridgeRegistryAddr() (string, error) { if nil == ethRelayer.x2EthDeployInfo { return "", errors.New("the relayer is not started yes") @@ -235,41 +235,41 @@ func (ethRelayer *Relayer4Ethereum) ShowBridgeRegistryAddr() (string, error) { return ethRelayer.x2EthDeployInfo.BridgeRegistry.Address.String(), nil } -//ShowLockStatics ... +// ShowLockStatics ... func (ethRelayer *Relayer4Ethereum) ShowLockStatics(tokenAddr string) (string, error) { return ethtxs.GetLockedFunds(ethRelayer.x2EthContracts.BridgeBank, tokenAddr) } -//ShowDepositStatics ... +// ShowDepositStatics ... func (ethRelayer *Relayer4Ethereum) ShowDepositStatics(tokenAddr string) (string, error) { return ethtxs.GetDepositFunds(ethRelayer.clientSpec, tokenAddr) } -//ShowTokenAddrBySymbol ... +// ShowTokenAddrBySymbol ... func (ethRelayer *Relayer4Ethereum) ShowTokenAddrBySymbol(tokenSymbol string) (string, error) { return ethtxs.GetToken2address(ethRelayer.x2EthContracts.BridgeBank, tokenSymbol) } -//IsProphecyPending ... +// IsProphecyPending ... func (ethRelayer *Relayer4Ethereum) IsProphecyPending(claimID [32]byte) (bool, error) { return ethtxs.IsProphecyPending(claimID, ethRelayer.ethValidator, ethRelayer.x2EthContracts.Chain33Bridge) } -//CreateBridgeToken ... +// CreateBridgeToken ... func (ethRelayer *Relayer4Ethereum) CreateBridgeToken(symbol string) (string, error) { ethRelayer.rwLock.RLock() defer ethRelayer.rwLock.RUnlock() return ethtxs.CreateBridgeToken(symbol, ethRelayer.clientSpec, ethRelayer.operatorInfo, ethRelayer.x2EthDeployInfo, ethRelayer.x2EthContracts) } -//CreateERC20Token ... +// CreateERC20Token ... func (ethRelayer *Relayer4Ethereum) CreateERC20Token(symbol string) (string, error) { ethRelayer.rwLock.RLock() defer ethRelayer.rwLock.RUnlock() return ethtxs.CreateERC20Token(symbol, ethRelayer.clientSpec, ethRelayer.operatorInfo) } -//MintERC20Token ... +// MintERC20Token ... func (ethRelayer *Relayer4Ethereum) MintERC20Token(tokenAddr, ownerAddr, amount string) (string, error) { bn := big.NewInt(1) bn, _ = bn.SetString(x2ethTypes.TrimZeroAndDot(amount), 10) @@ -278,35 +278,35 @@ func (ethRelayer *Relayer4Ethereum) MintERC20Token(tokenAddr, ownerAddr, amount return ethtxs.MintERC20Token(tokenAddr, ownerAddr, bn, ethRelayer.clientSpec, ethRelayer.operatorInfo) } -//ApproveAllowance ... +// ApproveAllowance ... func (ethRelayer *Relayer4Ethereum) ApproveAllowance(ownerPrivateKey, tokenAddr, amount string) (string, error) { bn := big.NewInt(1) bn, _ = bn.SetString(x2ethTypes.TrimZeroAndDot(amount), 10) return ethtxs.ApproveAllowance(ownerPrivateKey, tokenAddr, ethRelayer.x2EthDeployInfo.BridgeBank.Address, bn, ethRelayer.clientSpec) } -//Burn ... +// Burn ... func (ethRelayer *Relayer4Ethereum) Burn(ownerPrivateKey, tokenAddr, chain33Receiver, amount string) (string, error) { bn := big.NewInt(1) bn, _ = bn.SetString(x2ethTypes.TrimZeroAndDot(amount), 10) return ethtxs.Burn(ownerPrivateKey, tokenAddr, chain33Receiver, ethRelayer.x2EthDeployInfo.BridgeBank.Address, bn, ethRelayer.x2EthContracts.BridgeBank, ethRelayer.clientSpec) } -//BurnAsync ... +// BurnAsync ... func (ethRelayer *Relayer4Ethereum) BurnAsync(ownerPrivateKey, tokenAddr, chain33Receiver, amount string) (string, error) { bn := big.NewInt(1) bn, _ = bn.SetString(x2ethTypes.TrimZeroAndDot(amount), 10) return ethtxs.BurnAsync(ownerPrivateKey, tokenAddr, chain33Receiver, bn, ethRelayer.x2EthContracts.BridgeBank, ethRelayer.clientSpec) } -//TransferToken ... +// TransferToken ... func (ethRelayer *Relayer4Ethereum) TransferToken(tokenAddr, fromKey, toAddr, amount string) (string, error) { bn := big.NewInt(1) bn, _ = bn.SetString(x2ethTypes.TrimZeroAndDot(amount), 10) return ethtxs.TransferToken(tokenAddr, fromKey, toAddr, bn, ethRelayer.clientSpec) } -//GetDecimals ... +// GetDecimals ... func (ethRelayer *Relayer4Ethereum) GetDecimals(tokenAddr string) (uint8, error) { opts := &bind.CallOpts{ Pending: true, @@ -317,21 +317,21 @@ func (ethRelayer *Relayer4Ethereum) GetDecimals(tokenAddr string) (uint8, error) return bridgeToken.Decimals(opts) } -//LockEthErc20Asset ... +// LockEthErc20Asset ... func (ethRelayer *Relayer4Ethereum) LockEthErc20Asset(ownerPrivateKey, tokenAddr, amount string, chain33Receiver string) (string, error) { bn := big.NewInt(1) bn, _ = bn.SetString(x2ethTypes.TrimZeroAndDot(amount), 10) return ethtxs.LockEthErc20Asset(ownerPrivateKey, tokenAddr, chain33Receiver, bn, ethRelayer.clientSpec, ethRelayer.x2EthContracts.BridgeBank, ethRelayer.x2EthDeployInfo.BridgeBank.Address) } -//LockEthErc20AssetAsync ... +// LockEthErc20AssetAsync ... func (ethRelayer *Relayer4Ethereum) LockEthErc20AssetAsync(ownerPrivateKey, tokenAddr, amount string, chain33Receiver string) (string, error) { bn := big.NewInt(1) bn, _ = bn.SetString(x2ethTypes.TrimZeroAndDot(amount), 10) return ethtxs.LockEthErc20AssetAsync(ownerPrivateKey, tokenAddr, chain33Receiver, bn, ethRelayer.clientSpec, ethRelayer.x2EthContracts.BridgeBank) } -//ShowTxReceipt ... +// ShowTxReceipt ... func (ethRelayer *Relayer4Ethereum) ShowTxReceipt(hash string) (*types.Receipt, error) { txhash := common.HexToHash(hash) return ethRelayer.clientSpec.TransactionReceipt(context.Background(), txhash) @@ -634,7 +634,7 @@ func (ethRelayer *Relayer4Ethereum) subscribeEvent() { ethRelayer.bridgeBankSub = sub } -//IsValidatorActive ... +// IsValidatorActive ... func (ethRelayer *Relayer4Ethereum) IsValidatorActive(addr string) (bool, error) { re := regexp.MustCompile("^0x[0-9a-fA-F]{40}$") if !re.MatchString(addr) { @@ -646,7 +646,7 @@ func (ethRelayer *Relayer4Ethereum) IsValidatorActive(addr string) (bool, error) return active, err } -//ShowOperator ... +// ShowOperator ... func (ethRelayer *Relayer4Ethereum) ShowOperator() (string, error) { operator, err := ethtxs.GetOperator(ethRelayer.clientSpec, ethRelayer.ethValidator, ethRelayer.bridgeBankAddr) if nil != err { @@ -655,13 +655,13 @@ func (ethRelayer *Relayer4Ethereum) ShowOperator() (string, error) { return operator.String(), nil } -//QueryTxhashRelay2Eth ... +// QueryTxhashRelay2Eth ... func (ethRelayer *Relayer4Ethereum) QueryTxhashRelay2Eth() ebTypes.Txhashes { txhashs := ethRelayer.queryTxhashes([]byte(chain33ToEthTxHashPrefix)) return ebTypes.Txhashes{Txhash: txhashs} } -//QueryTxhashRelay2Chain33 ... +// QueryTxhashRelay2Chain33 ... func (ethRelayer *Relayer4Ethereum) QueryTxhashRelay2Chain33() ebTypes.Txhashes { txhashs := ethRelayer.queryTxhashes([]byte(eth2chain33TxHashPrefix)) return ebTypes.Txhashes{Txhash: txhashs} diff --git a/plugin/dapp/x2ethereum/ebrelayer/relayer/ethereum/store.go b/plugin/dapp/x2ethereum/ebrelayer/relayer/ethereum/store.go index c17d4efced..56b4959254 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/relayer/ethereum/store.go +++ b/plugin/dapp/x2ethereum/ebrelayer/relayer/ethereum/store.go @@ -87,12 +87,12 @@ func (ethRelayer *Relayer4Ethereum) getLogProcHeight(key []byte) uint64 { return height.Data } -//保存处理过的交易 +// 保存处理过的交易 func (ethRelayer *Relayer4Ethereum) setTxProcessed(txhash []byte) error { return ethRelayer.db.Set(txhash, []byte("1")) } -//判断是否已经被处理,如果能够在数据库中找到该笔交易,则认为已经被处理 +// 判断是否已经被处理,如果能够在数据库中找到该笔交易,则认为已经被处理 func (ethRelayer *Relayer4Ethereum) checkTxProcessed(txhash []byte) bool { _, err := ethRelayer.db.Get(txhash) return nil == err @@ -158,7 +158,7 @@ func (ethRelayer *Relayer4Ethereum) getLastBridgeBankProcessedHeight() ebTypes.E return logIndex } -//构建一个引导查询使用的bridgeBankTx +// 构建一个引导查询使用的bridgeBankTx func (ethRelayer *Relayer4Ethereum) initBridgeBankTx() { log, _ := ethRelayer.getEthTxEvent(0, 0) if nil != log { diff --git a/plugin/dapp/x2ethereum/ebrelayer/relayer/manager.go b/plugin/dapp/x2ethereum/ebrelayer/relayer/manager.go index d136578105..e49589116b 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/relayer/manager.go +++ b/plugin/dapp/x2ethereum/ebrelayer/relayer/manager.go @@ -23,14 +23,14 @@ var ( mlog = log15.New("relayer manager", "manager") ) -//status ... +// status ... const ( Locked = int32(1) Unlocked = int32(99) EncryptEnable = int64(1) ) -//Manager ... +// Manager ... type Manager struct { chain33Relayer *chain33.Relayer4Chain33 ethRelayer *ethereum.Relayer4Ethereum @@ -42,9 +42,9 @@ type Manager struct { decimalLru *lru.Cache } -//NewRelayerManager ... -//1.验证人的私钥需要通过cli命令行进行导入,且chain33和ethereum两种不同的验证人需要分别导入 -//2.显示或者重新替换原有的私钥首先需要通过passpin进行unlock的操作 +// NewRelayerManager ... +// 1.验证人的私钥需要通过cli命令行进行导入,且chain33和ethereum两种不同的验证人需要分别导入 +// 2.显示或者重新替换原有的私钥首先需要通过passpin进行unlock的操作 func NewRelayerManager(chain33Relayer *chain33.Relayer4Chain33, ethRelayer *ethereum.Relayer4Ethereum, db dbm.DB) *Manager { l, _ := lru.New(4096) manager := &Manager{ @@ -61,7 +61,7 @@ func NewRelayerManager(chain33Relayer *chain33.Relayer4Chain33, ethRelayer *ethe return manager } -//SetPassphase ... +// SetPassphase ... func (manager *Manager) SetPassphase(setPasswdReq relayerTypes.ReqSetPasswd, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -105,7 +105,7 @@ func (manager *Manager) SetPassphase(setPasswdReq relayerTypes.ReqSetPasswd, res return nil } -//ChangePassphase ... +// ChangePassphase ... func (manager *Manager) ChangePassphase(setPasswdReq relayerTypes.ReqChangePasswd, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -180,7 +180,7 @@ func (manager *Manager) ChangePassphase(setPasswdReq relayerTypes.ReqChangePassw return nil } -//Unlock 进行unlok操作 +// Unlock 进行unlok操作 func (manager *Manager) Unlock(passphase string, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -215,7 +215,7 @@ func (manager *Manager) Unlock(passphase string, result *interface{}) error { return nil } -//Lock 锁定操作,该操作一旦执行,就不能替换验证人的私钥,需要重新unlock之后才能修改 +// Lock 锁定操作,该操作一旦执行,就不能替换验证人的私钥,需要重新unlock之后才能修改 func (manager *Manager) Lock(param interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -230,7 +230,7 @@ func (manager *Manager) Lock(param interface{}, result *interface{}) error { return nil } -//ImportChain33RelayerPrivateKey 导入chain33relayer验证人的私钥,该私钥实际用于向ethereum提交验证交易时签名使用 +// ImportChain33RelayerPrivateKey 导入chain33relayer验证人的私钥,该私钥实际用于向ethereum提交验证交易时签名使用 func (manager *Manager) ImportChain33RelayerPrivateKey(importKeyReq relayerTypes.ImportKeyReq, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -251,7 +251,7 @@ func (manager *Manager) ImportChain33RelayerPrivateKey(importKeyReq relayerTypes return nil } -//GenerateEthereumPrivateKey 生成以太坊私钥 +// GenerateEthereumPrivateKey 生成以太坊私钥 func (manager *Manager) GenerateEthereumPrivateKey(param interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -268,7 +268,7 @@ func (manager *Manager) GenerateEthereumPrivateKey(param interface{}, result *in return nil } -//ImportChain33PrivateKey4EthRelayer 为ethrelayer导入chain33私钥,为向chain33发送交易时进行签名使用 +// ImportChain33PrivateKey4EthRelayer 为ethrelayer导入chain33私钥,为向chain33发送交易时进行签名使用 func (manager *Manager) ImportChain33PrivateKey4EthRelayer(privateKey string, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -285,7 +285,7 @@ func (manager *Manager) ImportChain33PrivateKey4EthRelayer(privateKey string, re return nil } -//ShowChain33RelayerValidator 显示在chain33中以验证人validator身份进行登录的地址 +// ShowChain33RelayerValidator 显示在chain33中以验证人validator身份进行登录的地址 func (manager *Manager) ShowChain33RelayerValidator(param interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -298,7 +298,7 @@ func (manager *Manager) ShowChain33RelayerValidator(param interface{}, result *i return nil } -//ShowEthRelayerValidator 显示在Ethereum中以验证人validator身份进行登录的地址 +// ShowEthRelayerValidator 显示在Ethereum中以验证人validator身份进行登录的地址 func (manager *Manager) ShowEthRelayerValidator(param interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -310,7 +310,7 @@ func (manager *Manager) ShowEthRelayerValidator(param interface{}, result *inter return nil } -//IsValidatorActive ... +// IsValidatorActive ... func (manager *Manager) IsValidatorActive(vallidatorAddr string, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -325,7 +325,7 @@ func (manager *Manager) IsValidatorActive(vallidatorAddr string, result *interfa return nil } -//ShowOperator ... +// ShowOperator ... func (manager *Manager) ShowOperator(param interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -337,7 +337,7 @@ func (manager *Manager) ShowOperator(param interface{}, result *interface{}) err return nil } -//DeployContrcts ... +// DeployContrcts ... func (manager *Manager) DeployContrcts(param interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -355,7 +355,7 @@ func (manager *Manager) DeployContrcts(param interface{}, result *interface{}) e return nil } -//CreateBridgeToken ... +// CreateBridgeToken ... func (manager *Manager) CreateBridgeToken(symbol string, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -373,7 +373,7 @@ func (manager *Manager) CreateBridgeToken(symbol string, result *interface{}) er return nil } -//CreateERC20Token ... +// CreateERC20Token ... func (manager *Manager) CreateERC20Token(symbol string, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -391,7 +391,7 @@ func (manager *Manager) CreateERC20Token(symbol string, result *interface{}) err return nil } -//MintErc20 ... +// MintErc20 ... func (manager *Manager) MintErc20(mintToken relayerTypes.MintToken, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -409,7 +409,7 @@ func (manager *Manager) MintErc20(mintToken relayerTypes.MintToken, result *inte return nil } -//ApproveAllowance ... +// ApproveAllowance ... func (manager *Manager) ApproveAllowance(approveAllowance relayerTypes.ApproveAllowance, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -427,7 +427,7 @@ func (manager *Manager) ApproveAllowance(approveAllowance relayerTypes.ApproveAl return nil } -//Burn ... +// Burn ... func (manager *Manager) Burn(burn relayerTypes.Burn, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -445,7 +445,7 @@ func (manager *Manager) Burn(burn relayerTypes.Burn, result *interface{}) error return nil } -//BurnAsync ... +// BurnAsync ... func (manager *Manager) BurnAsync(burn relayerTypes.Burn, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -463,7 +463,7 @@ func (manager *Manager) BurnAsync(burn relayerTypes.Burn, result *interface{}) e return nil } -//LockEthErc20AssetAsync ... +// LockEthErc20AssetAsync ... func (manager *Manager) LockEthErc20AssetAsync(lockEthErc20Asset relayerTypes.LockEthErc20, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -481,7 +481,7 @@ func (manager *Manager) LockEthErc20AssetAsync(lockEthErc20Asset relayerTypes.Lo return nil } -//LockEthErc20Asset ... +// LockEthErc20Asset ... func (manager *Manager) LockEthErc20Asset(lockEthErc20Asset relayerTypes.LockEthErc20, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -499,7 +499,7 @@ func (manager *Manager) LockEthErc20Asset(lockEthErc20Asset relayerTypes.LockEth return nil } -//IsProphecyPending ... +// IsProphecyPending ... func (manager *Manager) IsProphecyPending(claimID [32]byte, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -513,7 +513,7 @@ func (manager *Manager) IsProphecyPending(claimID [32]byte, result *interface{}) return nil } -//GetBalance ... +// GetBalance ... func (manager *Manager) GetBalance(balanceAddr relayerTypes.BalanceAddr, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -539,7 +539,7 @@ func (manager *Manager) GetBalance(balanceAddr relayerTypes.BalanceAddr, result return nil } -//ShowBridgeBankAddr ... +// ShowBridgeBankAddr ... func (manager *Manager) ShowBridgeBankAddr(para interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -554,7 +554,7 @@ func (manager *Manager) ShowBridgeBankAddr(para interface{}, result *interface{} return nil } -//ShowBridgeRegistryAddr ... +// ShowBridgeRegistryAddr ... func (manager *Manager) ShowBridgeRegistryAddr(para interface{}, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -569,7 +569,7 @@ func (manager *Manager) ShowBridgeRegistryAddr(para interface{}, result *interfa return nil } -//ShowLockStatics ... +// ShowLockStatics ... func (manager *Manager) ShowLockStatics(token relayerTypes.TokenStatics, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -592,7 +592,7 @@ func (manager *Manager) ShowLockStatics(token relayerTypes.TokenStatics, result return nil } -//ShowDepositStatics ... +// ShowDepositStatics ... func (manager *Manager) ShowDepositStatics(token relayerTypes.TokenStatics, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -615,7 +615,7 @@ func (manager *Manager) ShowDepositStatics(token relayerTypes.TokenStatics, resu return nil } -//ShowTokenAddrBySymbol ... +// ShowTokenAddrBySymbol ... func (manager *Manager) ShowTokenAddrBySymbol(token relayerTypes.TokenStatics, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -631,7 +631,7 @@ func (manager *Manager) ShowTokenAddrBySymbol(token relayerTypes.TokenStatics, r return nil } -//ShowTxReceipt ... +// ShowTxReceipt ... func (manager *Manager) ShowTxReceipt(txhash string, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -653,47 +653,47 @@ func (manager *Manager) checkPermission() error { return nil } -//ShowEthRelayer2EthTxs ... +// ShowEthRelayer2EthTxs ... func (manager *Manager) ShowEthRelayer2EthTxs(param interface{}, result *interface{}) error { *result = manager.ethRelayer.QueryTxhashRelay2Eth() return nil } -//ShowEthRelayer2Chain33Txs ... +// ShowEthRelayer2Chain33Txs ... func (manager *Manager) ShowEthRelayer2Chain33Txs(param interface{}, result *interface{}) error { *result = manager.ethRelayer.QueryTxhashRelay2Chain33() return nil } -//ShowChain33Relayer2EthTxs ... +// ShowChain33Relayer2EthTxs ... func (manager *Manager) ShowChain33Relayer2EthTxs(param interface{}, result *interface{}) error { *result = manager.chain33Relayer.QueryTxhashRelay2Eth() return nil } -//ShowTxsEth2chain33TxLock ... +// ShowTxsEth2chain33TxLock ... func (manager *Manager) ShowTxsEth2chain33TxLock(param interface{}, result *interface{}) error { return nil } -//ShowTxsEth2chain33TxBurn ... +// ShowTxsEth2chain33TxBurn ... func (manager *Manager) ShowTxsEth2chain33TxBurn(param interface{}, result *interface{}) error { return nil } -//ShowTxsChain33ToEthTxLock ... +// ShowTxsChain33ToEthTxLock ... func (manager *Manager) ShowTxsChain33ToEthTxLock(param interface{}, result *interface{}) error { return nil } -//ShowTxsChain33ToEthTxBurn ... +// ShowTxsChain33ToEthTxBurn ... func (manager *Manager) ShowTxsChain33ToEthTxBurn(param interface{}, result *interface{}) error { return nil } -//TransferToken ... +// TransferToken ... func (manager *Manager) TransferToken(transfer relayerTypes.TransferToken, result *interface{}) error { manager.mtx.Lock() defer manager.mtx.Unlock() @@ -708,7 +708,7 @@ func (manager *Manager) TransferToken(transfer relayerTypes.TransferToken, resul return nil } -//GetDecimals ... +// GetDecimals ... func (manager *Manager) GetDecimals(tokenAddr string) (int64, error) { if d, ok := manager.decimalLru.Get(tokenAddr); ok { mlog.Info("GetDecimals", "from cache", d) diff --git a/plugin/dapp/x2ethereum/ebrelayer/types/config.pb.go b/plugin/dapp/x2ethereum/ebrelayer/types/config.pb.go index 652c571372..a1f25baebc 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/types/config.pb.go +++ b/plugin/dapp/x2ethereum/ebrelayer/types/config.pb.go @@ -6,10 +6,12 @@ Package types is a generated protocol buffer package. It is generated from these files: + config.proto relayer.proto It has these top-level messages: + SyncTxConfig Log RelayerConfig diff --git a/plugin/dapp/x2ethereum/ebrelayer/types/info.go b/plugin/dapp/x2ethereum/ebrelayer/types/info.go index bcd6453778..693d4791d5 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/types/info.go +++ b/plugin/dapp/x2ethereum/ebrelayer/types/info.go @@ -1,9 +1,9 @@ package types -//Version4Relayer ... +// Version4Relayer ... const Version4Relayer = "0.1.0" -//setting +// setting const ( StatusPending = iota // Oracle : oracle contract diff --git a/plugin/dapp/x2ethereum/ebrelayer/types/relayer.pb.go b/plugin/dapp/x2ethereum/ebrelayer/types/relayer.pb.go index 28ab388fa3..15d21e8e39 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/types/relayer.pb.go +++ b/plugin/dapp/x2ethereum/ebrelayer/types/relayer.pb.go @@ -10,8 +10,9 @@ import proto "github.com/golang/protobuf/proto" var _ = proto.Marshal // 以太坊账户信息 -// privkey : 账户地址对应的私钥 -// addr :账户地址 +// +// privkey : 账户地址对应的私钥 +// addr :账户地址 type Account4Relayer struct { Privkey []byte `protobuf:"bytes,1,opt,name=privkey,proto3" json:"privkey,omitempty"` Addr string `protobuf:"bytes,2,opt,name=addr" json:"addr,omitempty"` diff --git a/plugin/dapp/x2ethereum/ebrelayer/utils/utils.go b/plugin/dapp/x2ethereum/ebrelayer/utils/utils.go index 478339a791..26612eee5d 100644 --- a/plugin/dapp/x2ethereum/ebrelayer/utils/utils.go +++ b/plugin/dapp/x2ethereum/ebrelayer/utils/utils.go @@ -37,7 +37,7 @@ func IsZeroAddress(address common.Address) bool { return address == common.HexToAddress(nullAddress) } -//IsValidPassWord 密码合法性校验,密码长度在8-30位之间。必须是数字+字母的组合 +// IsValidPassWord 密码合法性校验,密码长度在8-30位之间。必须是数字+字母的组合 func IsValidPassWord(password string) bool { pwLen := len(password) if pwLen < 8 || pwLen > 30 { @@ -71,7 +71,7 @@ func decodeInt64(int64bytes []byte) (int64, error) { return value.Data, nil } -//LoadInt64FromDB ... +// LoadInt64FromDB ... func LoadInt64FromDB(key []byte, db dbm.DB) (int64, error) { bytes, err := db.Get(key) if bytes == nil || err != nil { @@ -83,7 +83,7 @@ func LoadInt64FromDB(key []byte, db dbm.DB) (int64, error) { return decodeInt64(bytes) } -//QueryTxhashes ... +// QueryTxhashes ... func QueryTxhashes(prefix []byte, db dbm.DB) []string { kvdb := dbm.NewKVDB(db) hashes, err := kvdb.List(prefix, nil, 10, 1) @@ -98,17 +98,17 @@ func QueryTxhashes(prefix []byte, db dbm.DB) []string { return hashStrs } -//Addr2DecimalsKey ... +// Addr2DecimalsKey ... var ( Addr2DecimalsKey = []byte("prefix_for_Addr2Decimals") ) -//CalAddr2DecimalsPrefix ... +// CalAddr2DecimalsPrefix ... func CalAddr2DecimalsPrefix(tokenAddr string) []byte { return []byte(fmt.Sprintf("%s-%s", Addr2DecimalsKey, tokenAddr)) } -//GetDecimalsFromDB ... +// GetDecimalsFromDB ... func GetDecimalsFromDB(addr string, db dbm.DB) (int64, error) { res, err := db.Get(CalAddr2DecimalsPrefix(addr)) if err != nil { @@ -125,7 +125,7 @@ func GetDecimalsFromDB(addr string, db dbm.DB) (int64, error) { return 0, types.ErrNotFound } -//GetDecimalsFromNode ... +// GetDecimalsFromNode ... func GetDecimalsFromNode(addr string, nodeAddr string) (int64, error) { if addr == "0x0000000000000000000000000000000000000000" || addr == "" { return 18, nil diff --git a/plugin/dapp/x2ethereum/executor/exec.go b/plugin/dapp/x2ethereum/executor/exec.go index f5350abd0a..64cfab6155 100644 --- a/plugin/dapp/x2ethereum/executor/exec.go +++ b/plugin/dapp/x2ethereum/executor/exec.go @@ -29,7 +29,7 @@ func (x *x2ethereum) Exec_Eth2Chain33Lock(payload *x2eTy.Eth2Chain33, tx *types. return action.procEth2Chain33_lock(payload) } -//---------------- Chain33(eth/erc20)------> Ethereum -------------------// +// ---------------- Chain33(eth/erc20)------> Ethereum -------------------// // 在chain33端将铸的币销毁,返还给eth func (x *x2ethereum) Exec_Chain33ToEthBurn(payload *x2eTy.Chain33ToEth, tx *types.Transaction, index int) (*types.Receipt, error) { action := newAction(x, tx, int32(index)) @@ -39,7 +39,7 @@ func (x *x2ethereum) Exec_Chain33ToEthBurn(payload *x2eTy.Chain33ToEth, tx *type return action.procChain33ToEth_burn(payload) } -//---------------- Ethereum (bty) --> Chain33-------------------// +// ---------------- Ethereum (bty) --> Chain33-------------------// // 在eth端将铸的bty币销毁,返还给chain33 func (x *x2ethereum) Exec_Eth2Chain33Burn(payload *x2eTy.Eth2Chain33, tx *types.Transaction, index int) (*types.Receipt, error) { action := newAction(x, tx, int32(index)) @@ -52,7 +52,7 @@ func (x *x2ethereum) Exec_Eth2Chain33Burn(payload *x2eTy.Eth2Chain33, tx *types. return action.procEth2Chain33_burn(payload) } -//---------------- Chain33 --> Ethereum (bty) -------------------// +// ---------------- Chain33 --> Ethereum (bty) -------------------// // 在 ethereum 上为 chain33 铸币 func (x *x2ethereum) Exec_Chain33ToEthLock(payload *x2eTy.Chain33ToEth, tx *types.Transaction, index int) (*types.Receipt, error) { action := newAction(x, tx, int32(index)) diff --git a/plugin/dapp/x2ethereum/executor/exec_local.go b/plugin/dapp/x2ethereum/executor/exec_local.go index c7c9947cc3..9e68571936 100644 --- a/plugin/dapp/x2ethereum/executor/exec_local.go +++ b/plugin/dapp/x2ethereum/executor/exec_local.go @@ -68,7 +68,7 @@ func (x *x2ethereum) ExecLocal_SetConsensusThreshold(payload *x2eTy.MsgConsensus return x.addAutoRollBack(tx, dbSet.KV), nil } -//设置自动回滚 +// 设置自动回滚 func (x *x2ethereum) addAutoRollBack(tx *types.Transaction, kv []*types.KeyValue) *types.LocalDBSet { dbSet := &types.LocalDBSet{} dbSet.KV = x.AddRollbackKV(tx, tx.Execer, kv) diff --git a/plugin/dapp/x2ethereum/executor/prophecy.go b/plugin/dapp/x2ethereum/executor/prophecy.go index a0e5e628ba..5fc482b90b 100644 --- a/plugin/dapp/x2ethereum/executor/prophecy.go +++ b/plugin/dapp/x2ethereum/executor/prophecy.go @@ -8,7 +8,7 @@ import ( x2eTy "github.com/33cn/plugin/plugin/dapp/x2ethereum/types" ) -//NewProphecy ... +// NewProphecy ... func NewProphecy(id string) *x2eTy.ReceiptEthProphecy { status := new(x2eTy.ProphecyStatus) @@ -47,7 +47,7 @@ func AddClaim(prophecy *x2eTy.ReceiptEthProphecy, validator string, claim string } -//FindHighestClaim 遍历该prophecy所有claim,找出获得最多票数的claim +// FindHighestClaim 遍历该prophecy所有claim,找出获得最多票数的claim func FindHighestClaim(prophecy *x2eTy.ReceiptEthProphecy, validators map[string]int64) (string, int64, int64) { totalClaimsPower := int64(0) highestClaimPower := int64(-1) @@ -67,7 +67,7 @@ func FindHighestClaim(prophecy *x2eTy.ReceiptEthProphecy, validators map[string] return highestClaim, highestClaimPower, totalClaimsPower } -//NewOracleClaimContent ... +// NewOracleClaimContent ... func NewOracleClaimContent(chain33Receiver string, amount string, claimType, decimals int64) x2eTy.OracleClaimContent { return x2eTy.OracleClaimContent{ Chain33Receiver: chain33Receiver, @@ -77,7 +77,7 @@ func NewOracleClaimContent(chain33Receiver string, amount string, claimType, dec } } -//NewClaim ... +// NewClaim ... func NewClaim(id string, validatorAddress string, content string) x2eTy.OracleClaim { return x2eTy.OracleClaim{ ID: id, @@ -86,7 +86,7 @@ func NewClaim(id string, validatorAddress string, content string) x2eTy.OracleCl } } -//CreateOracleClaimFromEthClaim 通过ethchain33结构构造一个OracleClaim结构,包括生成唯一的ID +// CreateOracleClaimFromEthClaim 通过ethchain33结构构造一个OracleClaim结构,包括生成唯一的ID func CreateOracleClaimFromEthClaim(ethClaim x2eTy.Eth2Chain33) (x2eTy.OracleClaim, error) { if ethClaim.ClaimType != int64(x2eTy.LockClaimType) && ethClaim.ClaimType != int64(x2eTy.BurnClaimType) { return x2eTy.OracleClaim{}, x2eTy.ErrInvalidClaimType @@ -105,7 +105,7 @@ func CreateOracleClaimFromEthClaim(ethClaim x2eTy.Eth2Chain33) (x2eTy.OracleClai return claim, nil } -//CreateOracleClaimFromOracleString -- +// CreateOracleClaimFromOracleString -- func CreateOracleClaimFromOracleString(oracleClaimString string) (x2eTy.OracleClaimContent, error) { var oracleClaimContent x2eTy.OracleClaimContent diff --git a/plugin/dapp/x2ethereum/executor/x2ethereumaction.go b/plugin/dapp/x2ethereum/executor/x2ethereumaction.go index 168739e8e5..84a7c2d5e6 100644 --- a/plugin/dapp/x2ethereum/executor/x2ethereumaction.go +++ b/plugin/dapp/x2ethereum/executor/x2ethereumaction.go @@ -351,9 +351,9 @@ func (a *action) procMsgWithDrawFromExec(msgWithdrawFromExec *types.AssetsWithdr return receipt, nil } -//需要一笔交易来注册validator -//这里注册的validator的power之和可能不为1,需要在内部进行加权 -//返回的回执中,KV包含所有validator的power值,Log中包含本次注册的validator的power值 +// 需要一笔交易来注册validator +// 这里注册的validator的power之和可能不为1,需要在内部进行加权 +// 返回的回执中,KV包含所有validator的power值,Log中包含本次注册的validator的power值 func (a *action) procAddValidator(msgAddValidator *x2eTy.MsgValidator) (*types.Receipt, error) { elog.Info("procAddValidator", "start", msgAddValidator) diff --git a/plugin/dapp/x2ethereum/executor/x2ethereumdb.go b/plugin/dapp/x2ethereum/executor/x2ethereumdb.go index f2f933d547..c1fa66af36 100644 --- a/plugin/dapp/x2ethereum/executor/x2ethereumdb.go +++ b/plugin/dapp/x2ethereum/executor/x2ethereumdb.go @@ -11,13 +11,13 @@ import ( x2eTy "github.com/33cn/plugin/plugin/dapp/x2ethereum/types" ) -//Oracle ... +// Oracle ... type Oracle struct { db dbm.KV consensusThreshold int64 } -//NewOracle ... +// NewOracle ... func NewOracle(db dbm.KV, consensusThreshold int64) *Oracle { if consensusThreshold <= 0 || consensusThreshold > 100 { return nil @@ -28,7 +28,7 @@ func NewOracle(db dbm.KV, consensusThreshold int64) *Oracle { } } -//ProcessSuccessfulClaimForLock 处理经过审核的关于Lock的claim +// ProcessSuccessfulClaimForLock 处理经过审核的关于Lock的claim func (o *Oracle) ProcessSuccessfulClaimForLock(claim, execAddr string, accDB *account.DB) (*types.Receipt, error) { var receipt *types.Receipt oracleClaim, err := CreateOracleClaimFromOracleString(claim) @@ -53,7 +53,7 @@ func (o *Oracle) ProcessSuccessfulClaimForLock(claim, execAddr string, accDB *ac return nil, x2eTy.ErrInvalidClaimType } -//ProcessSuccessfulClaimForBurn 处理经过审核的关于Burn的claim +// ProcessSuccessfulClaimForBurn 处理经过审核的关于Burn的claim func (o *Oracle) ProcessSuccessfulClaimForBurn(claim, execAddr, tokenSymbol string, accDB *account.DB) (*types.Receipt, error) { oracleClaim, err := CreateOracleClaimFromOracleString(claim) if err != nil { @@ -98,7 +98,7 @@ func (o *Oracle) ProcessLock(address, to, execAddr, amount string, accDB *accoun return receipt, nil } -//ProcessAddValidator ... +// ProcessAddValidator ... // 对于相同的地址该如何处理? // 现有方案是相同地址就报错 func (o *Oracle) ProcessAddValidator(address string, power int64) (*types.Receipt, error) { @@ -142,7 +142,7 @@ func (o *Oracle) ProcessAddValidator(address string, power int64) (*types.Receip return receipt, nil } -//ProcessRemoveValidator ... +// ProcessRemoveValidator ... func (o *Oracle) ProcessRemoveValidator(address string) (*types.Receipt, error) { var exist bool receipt := new(types.Receipt) @@ -180,7 +180,7 @@ func (o *Oracle) ProcessRemoveValidator(address string) (*types.Receipt, error) return receipt, nil } -//ProcessModifyValidator 这里的power指的是修改后的power +// ProcessModifyValidator 这里的power指的是修改后的power func (o *Oracle) ProcessModifyValidator(address string, power int64) (*types.Receipt, error) { var exist bool receipt := new(types.Receipt) @@ -217,7 +217,7 @@ func (o *Oracle) ProcessModifyValidator(address string, power int64) (*types.Rec return receipt, nil } -//ProcessSetConsensusNeeded ... +// ProcessSetConsensusNeeded ... func (o *Oracle) ProcessSetConsensusNeeded(ConsensusThreshold int64) (int64, int64, error) { preCon := o.GetConsensusThreshold() o.SetConsensusThreshold(ConsensusThreshold) @@ -228,7 +228,7 @@ func (o *Oracle) ProcessSetConsensusNeeded(ConsensusThreshold int64) (int64, int return preCon, nowCon, nil } -//GetProphecy ... +// GetProphecy ... func (o *Oracle) GetProphecy(id string) (*x2eTy.ReceiptEthProphecy, error) { if id == "" { return nil, x2eTy.ErrInvalidIdentifier @@ -290,7 +290,7 @@ func (o *Oracle) checkProphecy(prophecy *x2eTy.ReceiptEthProphecy) error { return nil } -//ProcessClaim 处理接收到的ethchain33请求 +// ProcessClaim 处理接收到的ethchain33请求 func (o *Oracle) ProcessClaim(claim x2eTy.Eth2Chain33) (*x2eTy.ProphecyStatus, error) { oracleClaim, err := CreateOracleClaimFromEthClaim(claim) if err != nil { @@ -392,7 +392,7 @@ func (o *Oracle) processCompletion(prophecy *x2eTy.ReceiptEthProphecy, claimType return prophecy, nil } -//GetLastTotalPower Load the last total validator power. +// GetLastTotalPower Load the last total validator power. func (o *Oracle) GetLastTotalPower() (int64, error) { b, err := o.db.Get(x2eTy.CalLastTotalPowerPrefix()) if err != nil && err != types.ErrNotFound { @@ -408,7 +408,7 @@ func (o *Oracle) GetLastTotalPower() (int64, error) { return powers.TotalPower, nil } -//SetLastTotalPower Set the last total validator power. +// SetLastTotalPower Set the last total validator power. func (o *Oracle) SetLastTotalPower() error { var totalPower int64 validatorArrays, err := o.GetValidatorArray() @@ -429,7 +429,7 @@ func (o *Oracle) SetLastTotalPower() error { return nil } -//GetValidatorArray ... +// GetValidatorArray ... func (o *Oracle) GetValidatorArray() (*x2eTy.ValidatorList, error) { validatorsBytes, err := o.db.Get(x2eTy.CalValidatorMapsPrefix()) if err != nil { @@ -443,13 +443,13 @@ func (o *Oracle) GetValidatorArray() (*x2eTy.ValidatorList, error) { return &validatorArrays, nil } -//SetConsensusThreshold ... +// SetConsensusThreshold ... func (o *Oracle) SetConsensusThreshold(ConsensusThreshold int64) { o.consensusThreshold = ConsensusThreshold elog.Info("SetConsensusNeeded", "nowConsensusNeeded", o.consensusThreshold) } -//GetConsensusThreshold ... +// GetConsensusThreshold ... func (o *Oracle) GetConsensusThreshold() int64 { return o.consensusThreshold } diff --git a/plugin/dapp/x2ethereum/types/const.go b/plugin/dapp/x2ethereum/types/const.go index 9920fd6f79..62a15c4502 100644 --- a/plugin/dapp/x2ethereum/types/const.go +++ b/plugin/dapp/x2ethereum/types/const.go @@ -1,6 +1,6 @@ package types -//key +// key var ( ProphecyKey = []byte("prefix_for_Prophecy") Eth2Chain33Key = []byte("prefix_for_Eth2Chain33") @@ -60,10 +60,10 @@ const ( NameWithdrawFromExecAction = "WithdrawFromExec" ) -//DefaultConsensusNeeded ... +// DefaultConsensusNeeded ... const DefaultConsensusNeeded = int64(70) -//direct ... +// direct ... const ( DirEth2Chain33 = "eth2chain33" DirChain33ToEth = "chain33toeth" @@ -71,7 +71,7 @@ const ( BurnClaim = "burn" ) -//DirectionType type +// DirectionType type var DirectionType = [3]string{"", DirEth2Chain33, DirChain33ToEth} // query function name @@ -84,7 +84,7 @@ const ( FuncQueryRelayerBalance = "GetRelayerBalance" ) -//lock type +// lock type const ( LockClaimType = int32(1) BurnClaimType = int32(2) diff --git a/plugin/dapp/x2ethereum/types/errors.go b/plugin/dapp/x2ethereum/types/errors.go index cc9fc70209..3383c2ae88 100644 --- a/plugin/dapp/x2ethereum/types/errors.go +++ b/plugin/dapp/x2ethereum/types/errors.go @@ -2,7 +2,7 @@ package types import "errors" -//err ... +// err ... var ( ErrInvalidClaimType = errors.New("invalid claim type provided") ErrInvalidEthSymbol = errors.New("invalid symbol provided, symbol \"eth\" must have null address set as token contract address") @@ -31,7 +31,7 @@ var ( ErrInvalidPower = errors.New("This power is invalid") ) -//common +// common var ( ErrSetKV = errors.New("Set KV error") ) diff --git a/plugin/dapp/x2ethereum/types/kv.go b/plugin/dapp/x2ethereum/types/kv.go index a805e4cbf2..9cd577306e 100644 --- a/plugin/dapp/x2ethereum/types/kv.go +++ b/plugin/dapp/x2ethereum/types/kv.go @@ -15,52 +15,52 @@ var ( KeyPrefixLocalDB = "LODB-x2ethereum-" ) -//CalProphecyPrefix ... +// CalProphecyPrefix ... func CalProphecyPrefix(id string) []byte { return []byte(KeyPrefixStateDB + string(ProphecyKey) + id) } -//CalEth2Chain33Prefix ... +// CalEth2Chain33Prefix ... func CalEth2Chain33Prefix() []byte { return []byte(KeyPrefixStateDB + string(Eth2Chain33Key)) } -//CalWithdrawEthPrefix ... +// CalWithdrawEthPrefix ... func CalWithdrawEthPrefix() []byte { return []byte(KeyPrefixStateDB + string(WithdrawEthKey)) } -//CalChain33ToEthPrefix ... +// CalChain33ToEthPrefix ... func CalChain33ToEthPrefix() []byte { return []byte(KeyPrefixStateDB + string(Chain33ToEthKey)) } -//CalWithdrawChain33Prefix ... +// CalWithdrawChain33Prefix ... func CalWithdrawChain33Prefix() []byte { return []byte(KeyPrefixStateDB + string(WithdrawChain33Key)) } -//CalValidatorMapsPrefix ... +// CalValidatorMapsPrefix ... func CalValidatorMapsPrefix() []byte { return []byte(KeyPrefixStateDB + string(ValidatorMapsKey)) } -//CalLastTotalPowerPrefix ... +// CalLastTotalPowerPrefix ... func CalLastTotalPowerPrefix() []byte { return []byte(KeyPrefixStateDB + string(LastTotalPowerKey)) } -//CalConsensusThresholdPrefix ... +// CalConsensusThresholdPrefix ... func CalConsensusThresholdPrefix() []byte { return []byte(KeyPrefixStateDB + string(ConsensusThresholdKey)) } -//CalTokenSymbolTotalLockOrBurnAmount ... +// CalTokenSymbolTotalLockOrBurnAmount ... func CalTokenSymbolTotalLockOrBurnAmount(symbol, tokenAddress, direction, txType string) []byte { return []byte(KeyPrefixLocalDB + string(TokenSymbolTotalLockOrBurnAmountKey) + direction + "-" + txType + "-" + strings.ToLower(symbol) + "-" + strings.ToLower(tokenAddress)) } -//CalTokenSymbolToTokenAddress ... +// CalTokenSymbolToTokenAddress ... func CalTokenSymbolToTokenAddress(symbol string) []byte { return []byte(KeyPrefixLocalDB + string(TokenSymbolToTokenAddressKey) + strings.ToLower(symbol)) } diff --git a/plugin/dapp/x2ethereum/types/utils.go b/plugin/dapp/x2ethereum/types/utils.go index 5de2d71a69..888a21a8fb 100644 --- a/plugin/dapp/x2ethereum/types/utils.go +++ b/plugin/dapp/x2ethereum/types/utils.go @@ -10,7 +10,7 @@ import ( "github.com/33cn/chain33/common/address" ) -//MultiplySpecifyTimes ... +// MultiplySpecifyTimes ... func MultiplySpecifyTimes(start float64, time int64) float64 { for i := 0; i < int(time); i++ { start *= 10 @@ -18,7 +18,7 @@ func MultiplySpecifyTimes(start float64, time int64) float64 { return start } -//Toeth ... +// Toeth ... func Toeth(amount string, decimal int64) float64 { bf := big.NewFloat(0) @@ -32,7 +32,7 @@ func Toeth(amount string, decimal int64) float64 { return f } -//ToWei 将eth单位的金额转为wei单位 +// ToWei 将eth单位的金额转为wei单位 func ToWei(amount float64, decimal int64) *big.Int { var ok bool @@ -49,7 +49,7 @@ func ToWei(amount float64, decimal int64) *big.Int { return nil } -//TrimZeroAndDot ... +// TrimZeroAndDot ... func TrimZeroAndDot(s string) string { if strings.Contains(s, ".") { var trimDotStr string @@ -61,7 +61,7 @@ func TrimZeroAndDot(s string) string { return s } -//CheckPower ... +// CheckPower ... func CheckPower(power int64) bool { if power <= 0 || power > 100 { return false @@ -69,7 +69,7 @@ func CheckPower(power int64) bool { return true } -//DivideDot ... +// DivideDot ... func DivideDot(in string) (left, right string, err error) { if strings.Contains(in, ".") { ss := strings.Split(in, ".") @@ -78,7 +78,7 @@ func DivideDot(in string) (left, right string, err error) { return "", "", errors.New("Divide error") } -//IsExecAddrMatch ... +// IsExecAddrMatch ... func IsExecAddrMatch(name string, to string) bool { toaddr := address.ExecAddress(name) return toaddr == to diff --git a/plugin/dapp/x2ethereum/types/x2ethereum.go b/plugin/dapp/x2ethereum/types/x2ethereum.go index 898dcc3290..087555ae32 100644 --- a/plugin/dapp/x2ethereum/types/x2ethereum.go +++ b/plugin/dapp/x2ethereum/types/x2ethereum.go @@ -67,12 +67,12 @@ func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(X2ethereumX, NewType(cfg)) } -//X2ethereumType ... +// X2ethereumType ... type X2ethereumType struct { types.ExecTypeBase } -//NewType ... +// NewType ... func NewType(cfg *types.Chain33Config) *X2ethereumType { c := &X2ethereumType{} c.SetChild(c) @@ -80,7 +80,7 @@ func NewType(cfg *types.Chain33Config) *X2ethereumType { return c } -//GetName ... +// GetName ... func (x *X2ethereumType) GetName() string { return X2ethereumX } diff --git a/plugin/dapp/zksync/commands/commands.go b/plugin/dapp/zksync/commands/commands.go index 9dc82489fc..a3af32241b 100644 --- a/plugin/dapp/zksync/commands/commands.go +++ b/plugin/dapp/zksync/commands/commands.go @@ -491,7 +491,7 @@ func setPubKey(cmd *cobra.Command, args []string) { paraName, _ := cmd.Flags().GetString("paraName") rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") if pubkeyT > 0 && (len(pubkeyX) == 0 || len(pubkeyY) == 0) { - fmt.Fprintln(os.Stderr, fmt.Sprintf("set proxy pubkey, need set pubkeyX pubkeyY")) + fmt.Fprintln(os.Stderr, "set proxy pubkey, need set pubkeyX pubkeyY") return } diff --git a/plugin/dapp/zksync/commands/l2txs/fetchBlock.go b/plugin/dapp/zksync/commands/l2txs/fetchBlock.go index 680a090d30..a15c18a4d1 100644 --- a/plugin/dapp/zksync/commands/l2txs/fetchBlock.go +++ b/plugin/dapp/zksync/commands/l2txs/fetchBlock.go @@ -65,8 +65,8 @@ func NewMainChainClient(paraRemoteGrpcClient string) chain33Ty.Chain33Client { return grpcClient } -//该命令用于从区块链获取包含l2交易的区块 -//./chain33-cli zksync sendl2 fetch -s 800 -e 6015 -p . --rpc_laddr 172.18.0.6:8902 +// 该命令用于从区块链获取包含l2交易的区块 +// ./chain33-cli zksync sendl2 fetch -s 800 -e 6015 -p . --rpc_laddr 172.18.0.6:8902 func fetchL2BlockCmd() *cobra.Command { cmd := &cobra.Command{ Use: "fetch", diff --git a/plugin/dapp/zksync/commands/l2txs/setPubKey.go b/plugin/dapp/zksync/commands/l2txs/setPubKey.go index 76900daddf..565f4da392 100644 --- a/plugin/dapp/zksync/commands/l2txs/setPubKey.go +++ b/plugin/dapp/zksync/commands/l2txs/setPubKey.go @@ -42,7 +42,7 @@ func setPubKey(cmd *cobra.Command, args []string) { keys := strings.Split(privateKeys, ",") if pubkeyT > 0 && (len(pubkeyX) == 0 || len(pubkeyY) == 0) { - _, _ = fmt.Fprintln(os.Stderr, fmt.Sprintf("set proxy pubkey, need set pubkeyX pubkeyY")) + _, _ = fmt.Fprintln(os.Stderr, "set proxy pubkey, need set pubkeyX pubkeyY") } if len(ids) != len(keys) { diff --git a/plugin/dapp/zksync/commands/l2txs/utils.go b/plugin/dapp/zksync/commands/l2txs/utils.go index 5df7537948..ac3b0d97bc 100644 --- a/plugin/dapp/zksync/commands/l2txs/utils.go +++ b/plugin/dapp/zksync/commands/l2txs/utils.go @@ -12,10 +12,10 @@ import ( chain33Crypto "github.com/33cn/chain33/common/crypto" "github.com/33cn/chain33/system/crypto/secp256k1" "github.com/33cn/chain33/types" + "github.com/33cn/plugin/plugin/crypto/legacymimc" pt "github.com/33cn/plugin/plugin/dapp/paracross/types" zksyncTypes "github.com/33cn/plugin/plugin/dapp/zksync/types" "github.com/33cn/plugin/plugin/dapp/zksync/wallet" - "github.com/33cn/plugin/plugin/crypto/legacymimc" "github.com/consensys/gnark-crypto/ecc/bn254/twistededwards/eddsa" "github.com/golang/protobuf/proto" ) diff --git a/plugin/dapp/zksync/commands/proof.go b/plugin/dapp/zksync/commands/proof.go index 46436c65b2..6af03ce4a9 100644 --- a/plugin/dapp/zksync/commands/proof.go +++ b/plugin/dapp/zksync/commands/proof.go @@ -382,49 +382,47 @@ func getZkCommitProofList(cmd *cobra.Command, args []string) { ctx.Run() } -// -//func getProofWitnessCmd() *cobra.Command { -// cmd := &cobra.Command{ -// Use: "witness", -// Short: "get account's proof witness at current height for specific token", -// Run: getProofWitness, +// func getProofWitnessCmd() *cobra.Command { +// cmd := &cobra.Command{ +// Use: "witness", +// Short: "get account's proof witness at current height for specific token", +// Run: getProofWitness, +// } +// getProofWitnessFlag(cmd) +// return cmd // } -// getProofWitnessFlag(cmd) -// return cmd -//} // -//func getProofWitnessFlag(cmd *cobra.Command) { -// cmd.Flags().Uint64P("account", "a", 0, "account id") -// cmd.MarkFlagRequired("account") -// cmd.Flags().Uint64P("token", "t", 0, "token id") -// cmd.MarkFlagRequired("token") -// cmd.Flags().Uint64P("chainTitleId", "n", 0, "chain title id") +// func getProofWitnessFlag(cmd *cobra.Command) { +// cmd.Flags().Uint64P("account", "a", 0, "account id") +// cmd.MarkFlagRequired("account") +// cmd.Flags().Uint64P("token", "t", 0, "token id") +// cmd.MarkFlagRequired("token") +// cmd.Flags().Uint64P("chainTitleId", "n", 0, "chain title id") // -//} +// } // -//func getProofWitness(cmd *cobra.Command, args []string) { -// rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") -// account, _ := cmd.Flags().GetUint64("account") -// token, _ := cmd.Flags().GetUint64("token") -// chainTitleId, _ := cmd.Flags().GetUint64("chainTitleId") +// func getProofWitness(cmd *cobra.Command, args []string) { +// rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr") +// account, _ := cmd.Flags().GetUint64("account") +// token, _ := cmd.Flags().GetUint64("token") +// chainTitleId, _ := cmd.Flags().GetUint64("chainTitleId") // -// var params rpctypes.Query4Jrpc +// var params rpctypes.Query4Jrpc // -// params.Execer = zt.Zksync -// req := &zt.ZkReqExistenceProof{ -// AccountId: account, -// TokenId: token, -// ChainTitleId: chainTitleId, -// } +// params.Execer = zt.Zksync +// req := &zt.ZkReqExistenceProof{ +// AccountId: account, +// TokenId: token, +// ChainTitleId: chainTitleId, +// } // -// params.FuncName = "GetCurrentProof" -// params.Payload = types.MustPBToJSON(req) -// -// var resp zt.ZkProofWitness -// ctx := jsonclient.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &resp) -// ctx.Run() -//} +// params.FuncName = "GetCurrentProof" +// params.Payload = types.MustPBToJSON(req) // +// var resp zt.ZkProofWitness +// ctx := jsonclient.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &resp) +// ctx.Run() +// } func getExistProofCmd() *cobra.Command { cmd := &cobra.Command{ Use: "exist", diff --git a/plugin/dapp/zksync/executor/accountTree.go b/plugin/dapp/zksync/executor/accountTree.go index 39c66b6830..41fe534c4e 100644 --- a/plugin/dapp/zksync/executor/accountTree.go +++ b/plugin/dapp/zksync/executor/accountTree.go @@ -10,9 +10,9 @@ import ( dbm "github.com/33cn/chain33/common/db" "github.com/33cn/chain33/common/db/table" "github.com/33cn/chain33/types" + "github.com/33cn/plugin/plugin/crypto/legacymimc" "github.com/33cn/plugin/plugin/dapp/mix/executor/merkletree" zt "github.com/33cn/plugin/plugin/dapp/zksync/types" - "github.com/33cn/plugin/plugin/crypto/legacymimc" "github.com/pkg/errors" ) @@ -394,7 +394,7 @@ func GetLeafByAccountId(db dbm.KV, accountId uint64) (*zt.Leaf, error) { func GetLeafByEthAddress(db dbm.KV, ethAddress string) ([]*zt.Leaf, error) { accountTable := NewAccountTreeTable(db) - rows, err := accountTable.ListIndex("eth_address", []byte(fmt.Sprintf("%s", ethAddress)), nil, 1000, dbm.ListASC) + rows, err := accountTable.ListIndex("eth_address", []byte(ethAddress), nil, 1000, dbm.ListASC) datas := make([]*zt.Leaf, 0) if err != nil { @@ -415,7 +415,7 @@ func GetLeafByEthAddress(db dbm.KV, ethAddress string) ([]*zt.Leaf, error) { func GetLeafByChain33Address(db dbm.KV, chain33Addr string) ([]*zt.Leaf, error) { accountTable := NewAccountTreeTable(db) - rows, err := accountTable.ListIndex("chain33_address", []byte(fmt.Sprintf("%s", chain33Addr)), nil, 1000, dbm.ListASC) + rows, err := accountTable.ListIndex("chain33_address", []byte(chain33Addr), nil, 1000, dbm.ListASC) datas := make([]*zt.Leaf, 0) if err != nil { diff --git a/plugin/dapp/zksync/executor/exec_local.go b/plugin/dapp/zksync/executor/exec_local.go index 36be9f6aba..3a4699befe 100644 --- a/plugin/dapp/zksync/executor/exec_local.go +++ b/plugin/dapp/zksync/executor/exec_local.go @@ -5,12 +5,12 @@ import ( zt "github.com/33cn/plugin/plugin/dapp/zksync/types" ) -//ExecLocal_Deposit asset withdraw local db process +// ExecLocal_Deposit asset withdraw local db process func (z *zksync) ExecLocal_Deposit(payload *zt.ZkDeposit, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return z.execAutoLocalZksync(tx, receiptData, index) } -//ExecLocal_Withdraw asset withdraw local db process +// ExecLocal_Withdraw asset withdraw local db process func (z *zksync) ExecLocal_Withdraw(payload *zt.ZkWithdraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return z.execAutoLocalZksync(tx, receiptData, index) } @@ -20,7 +20,7 @@ func (z *zksync) ExecLocal_ContractToTree(payload *zt.ZkContractToTree, tx *type return z.execAutoLocalZksync(tx, receiptData, index) } -//ExecLocal_Authorize asset withdraw local db process +// ExecLocal_Authorize asset withdraw local db process func (z *zksync) ExecLocal_TreeToContract(payload *zt.ZkTreeToContract, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { return z.execAutoLocalZksync(tx, receiptData, index) } diff --git a/plugin/dapp/zksync/executor/kv.go b/plugin/dapp/zksync/executor/kv.go index 987d3deac0..9954cf4633 100644 --- a/plugin/dapp/zksync/executor/kv.go +++ b/plugin/dapp/zksync/executor/kv.go @@ -8,7 +8,7 @@ import ( ) func GetAccountIdPrimaryKeyPrefix() string { - return fmt.Sprintf("%s", KeyPrefixStateDB+"accountId-") + return KeyPrefixStateDB + "accountId-" } func GetAccountIdPrimaryKey(accountId uint64) []byte { @@ -29,7 +29,7 @@ func GetTokenPrimaryKey(accountId uint64, tokenId uint64) []byte { } func GetTokenPrimaryKeyPrefix() string { - return fmt.Sprintf("%s", KeyPrefixStateDB+"token-") + return KeyPrefixStateDB + "token-" } func GetNFTIdPrimaryKey(nftTokenId uint64) []byte { @@ -37,7 +37,7 @@ func GetNFTIdPrimaryKey(nftTokenId uint64) []byte { } func GetNFTHashPrimaryKey(nftHash string) []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"nftHash-"+nftHash)) + return []byte(KeyPrefixStateDB + "nftHash-" + nftHash) } func GetRootIndexPrimaryKey(rootIndex uint64) []byte { @@ -45,33 +45,33 @@ func GetRootIndexPrimaryKey(rootIndex uint64) []byte { } func GetAccountTreeKey() []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"accountTree")) + return []byte(KeyPrefixStateDB + "accountTree") } func getVerifyKey() []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"-verifyKey")) + return []byte(KeyPrefixStateDB + "-verifyKey") } func getVerifier() []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"-"+zt.ZkVerifierKey)) + return []byte(KeyPrefixStateDB + "-" + zt.ZkVerifierKey) } func getLastOnChainProofIdKey() []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"-lastOnChainProofId")) + return []byte(KeyPrefixStateDB + "-lastOnChainProofId") } -//last eth priority id key +// last eth priority id key func getEthPriorityQueueKey() []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"priorityQueue")) + return []byte(KeyPrefixStateDB + "priorityQueue") } -//特意把title放后面,方便按id=1搜索所有的chain +// 特意把title放后面,方便按id=1搜索所有的chain func getProofIdCommitProofKey(proofId uint64) []byte { return []byte(fmt.Sprintf("%016d", proofId)) } func getRootCommitProofKey(root string) []byte { - return []byte(fmt.Sprintf("%s", root)) + return []byte(root) } func getHistoryAccountTreeKey(proofId, accountId uint64) []byte { @@ -83,56 +83,56 @@ func getZkFeeKey(actionTy int32, tokenId uint64) []byte { } func CalcLatestAccountIDKey() []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"latestAccountID")) + return []byte(KeyPrefixStateDB + "latestAccountID") } func getExodusModeKey() []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"exodusMode")) + return []byte(KeyPrefixStateDB + "exodusMode") } -//GetTokenSymbolKey tokenId 对应symbol +// GetTokenSymbolKey tokenId 对应symbol func GetTokenSymbolKey(tokenId string) []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"tokenId-"+tokenId)) + return []byte(KeyPrefixStateDB + "tokenId-" + tokenId) } -//GetTokenSymbolIdKey token symbol 对应id +// GetTokenSymbolIdKey token symbol 对应id func GetTokenSymbolIdKey(symbol string) []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"tokenSym-"+symbol)) + return []byte(KeyPrefixStateDB + "tokenSym-" + symbol) } func getLastProofIdKey() []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"-lastProof")) + return []byte(KeyPrefixStateDB + "-lastProof") } func getMaxRecordProofIdKey() []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"-maxRecordProofId")) + return []byte(KeyPrefixStateDB + "-maxRecordProofId") } func getProofIdKey(id uint64) []byte { return []byte(fmt.Sprintf("%s%022d", KeyPrefixStateDB+"-ProofId", id)) } -//the first L2 op that not be verified by proof +// the first L2 op that not be verified by proof func getL2FirstQueueIdKey() []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"-L2FirstQueId")) + return []byte(KeyPrefixStateDB + "-L2FirstQueId") } -//the last op that queued to L2, 从0开始 +// the last op that queued to L2, 从0开始 func getL2LastQueueIdKey() []byte { - return []byte(fmt.Sprintf("%s", KeyPrefixStateDB+"-L2LastQueId")) + return []byte(KeyPrefixStateDB + "-L2LastQueId") } -//the specific L2 op queue id data key +// the specific L2 op queue id data key func getL2QueueIdKey(id int64) []byte { return []byte(fmt.Sprintf("%s%022d", KeyPrefixStateDB+"-L2QueueId", id)) } -//the proof id to the end first queue id key, the end first queue id == last pubdata's operation +// the proof id to the end first queue id key, the end first queue id == last pubdata's operation func getProofId2QueueIdKey(proofID uint64) []byte { return []byte(fmt.Sprintf("%s%022d", KeyPrefixStateDB+"-proof2queueId", proofID)) } -//the proof id to the end first queue id key, the end first queue id == last pubdata's operation +// the proof id to the end first queue id key, the end first queue id == last pubdata's operation func getL1PriorityId2QueueIdKey(priorityId int64) []byte { return []byte(fmt.Sprintf("%s%022d", KeyPrefixStateDB+"-priority2QueId", priorityId)) } diff --git a/plugin/dapp/zksync/executor/tables.go b/plugin/dapp/zksync/executor/tables.go index a1336f1599..3f4f16ff18 100644 --- a/plugin/dapp/zksync/executor/tables.go +++ b/plugin/dapp/zksync/executor/tables.go @@ -44,12 +44,12 @@ func NewAccountTreeRow() *AccountTreeRow { return &AccountTreeRow{Leaf: &zt.Leaf{}} } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (r *AccountTreeRow) CreateRow() *table.Row { return &table.Row{Data: &zt.Leaf{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *AccountTreeRow) SetPayload(data types.Message) error { if txdata, ok := data.(*zt.Leaf); ok { r.Leaf = txdata @@ -58,19 +58,19 @@ func (r *AccountTreeRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *AccountTreeRow) Get(key string) ([]byte, error) { if key == "address" { return GetLocalChain33EthPrimaryKey(r.GetChain33Addr(), r.GetEthAddress()), nil } else if key == "chain33_address" { - return []byte(fmt.Sprintf("%s", address.FormatAddrKey(r.GetChain33Addr()))), nil + return address.FormatAddrKey(r.GetChain33Addr()), nil } else if key == "eth_address" { - return []byte(fmt.Sprintf("%s", address.FormatAddrKey(r.GetEthAddress()))), nil + return address.FormatAddrKey(r.GetEthAddress()), nil } return nil, types.ErrNotFound } -//目前似乎没啥用 +// 目前似乎没啥用 var opt_zksync_info = &table.Option{ Prefix: KeyPrefixLocalDB, Name: "zksync", @@ -97,12 +97,12 @@ func NewZksyncInfoRow() *ZksyncInfoRow { return &ZksyncInfoRow{AccountTokenBalanceReceipt: &zt.AccountTokenBalanceReceipt{}} } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (r *ZksyncInfoRow) CreateRow() *table.Row { return &table.Row{Data: &zt.AccountTokenBalanceReceipt{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *ZksyncInfoRow) SetPayload(data types.Message) error { if txdata, ok := data.(*zt.AccountTokenBalanceReceipt); ok { r.AccountTokenBalanceReceipt = txdata @@ -111,7 +111,7 @@ func (r *ZksyncInfoRow) SetPayload(data types.Message) error { return types.ErrTypeAsset } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *ZksyncInfoRow) Get(key string) ([]byte, error) { if key == "account_token_id" { return []byte(fmt.Sprintf("%016d.%016d", r.GetAccountId(), r.GetTokenId())), nil @@ -149,12 +149,12 @@ func NewCommitProofRow() *CommitProofRow { return &CommitProofRow{ZkCommitProof: &zt.ZkCommitProof{}} } -//CreateRow 新建数据行 +// CreateRow 新建数据行 func (r *CommitProofRow) CreateRow() *table.Row { return &table.Row{Data: &zt.ZkCommitProof{}} } -//SetPayload 设置数据 +// SetPayload 设置数据 func (r *CommitProofRow) SetPayload(data types.Message) error { if txdata, ok := data.(*zt.ZkCommitProof); ok { r.ZkCommitProof = txdata @@ -170,12 +170,12 @@ func (r *CommitProofRow) isProofNeedOnChain() int { return 0 } -//Get 按照indexName 查询 indexValue +// Get 按照indexName 查询 indexValue func (r *CommitProofRow) Get(key string) ([]byte, error) { if key == "proofId" { return []byte(fmt.Sprintf("%016d", r.GetProofId())), nil } else if key == "root" { - return []byte(fmt.Sprintf("%s", r.GetNewTreeRoot())), nil + return []byte(r.GetNewTreeRoot()), nil } else if key == "endHeight" { return []byte(fmt.Sprintf("%016d", r.GetBlockEnd())), nil } else if key == "commitHeight" { diff --git a/plugin/dapp/zksync/executor/util.go b/plugin/dapp/zksync/executor/util.go index c596ed2605..6b728e2225 100644 --- a/plugin/dapp/zksync/executor/util.go +++ b/plugin/dapp/zksync/executor/util.go @@ -27,7 +27,7 @@ func GetL2FirstQueueId(db dbm.KV) (int64, error) { return id.Data, nil } -//L2 queue id 从1开始编号,跟L1 priority 不同,后者为了和eth合约编号保持一致 +// L2 queue id 从1开始编号,跟L1 priority 不同,后者为了和eth合约编号保持一致 func GetL2LastQueueId(db dbm.KV) (int64, error) { key := getL2LastQueueIdKey() r, err := db.Get(key) @@ -59,7 +59,7 @@ func GetL2QueueIdOp(db dbm.KV, id int64) (*zt.ZkOperation, error) { return &data, nil } -//GetProofId2QueueId proof中的pubdata 对应的operation的start/end queueId +// GetProofId2QueueId proof中的pubdata 对应的operation的start/end queueId func GetProofId2QueueId(db dbm.KV, id uint64) (*zt.ProofId2QueueIdData, error) { key := getProofId2QueueIdKey(id) r, err := db.Get(key) @@ -358,9 +358,9 @@ func checkSameMintNFT(queueOp, pubDataOp *zt.ZkOperation) error { return errors.Wrapf(types.ErrInvalidParam, "mintNFT recv acctId queue=%d, pub=%d", q.RecipientID, p.RecipientID) } if q.ErcProtocol != p.ErcProtocol { - return errors.Wrapf(types.ErrInvalidParam, "mintNFT protocal queue=%d, pub=%d", q.ErcProtocol, p.ErcProtocol) + return errors.Wrapf(types.ErrInvalidParam, "mintNFT protocol queue=%d, pub=%d", q.ErcProtocol, p.ErcProtocol) } - for i, _ := range q.ContentHash { + for i := range q.ContentHash { if q.ContentHash[i] != p.ContentHash[i] { return errors.Wrapf(types.ErrInvalidParam, "mintNFT contentHash i=%d queue=%s, pub=%s", i, q.ContentHash[i], p.ContentHash[i]) } @@ -394,9 +394,9 @@ func checkSameWithdrawNFT(queueOp, pubDataOp *zt.ZkOperation) error { return errors.Wrapf(types.ErrInvalidParam, "withdrawNFT withdraw amount queue=%d, pub=%d", q.WithdrawAmount, p.WithdrawAmount) } if q.ErcProtocol != p.ErcProtocol { - return errors.Wrapf(types.ErrInvalidParam, "withdrawNFT protocal queue=%d, pub=%d", q.ErcProtocol, p.ErcProtocol) + return errors.Wrapf(types.ErrInvalidParam, "withdrawNFT protocol queue=%d, pub=%d", q.ErcProtocol, p.ErcProtocol) } - for i, _ := range q.ContentHash { + for i := range q.ContentHash { if q.ContentHash[i] != p.ContentHash[i] { return errors.Wrapf(types.ErrInvalidParam, "withdrawNFT contentHash i=%d queue=%s, pub=%s", i, q.ContentHash[i], p.ContentHash[i]) } @@ -463,7 +463,7 @@ func checkPackValue(amount string, manMaxBitWidth int64) error { return nil } -//根据系统和token精度,计算合约转化为二层tree侧的amount,合约侧amount都是系统精度 +// 根据系统和token精度,计算合约转化为二层tree侧的amount,合约侧amount都是系统精度 func GetTreeSideAmount(amount, totalAmount, fee string, sysDecimal, tokenDecimal int) (amount4Tree, totalAmount4Tree, feeAmount4Tree string, err error) { amount4Tree, err = TransferDecimalAmount(amount, sysDecimal, tokenDecimal) if err != nil { @@ -488,7 +488,7 @@ func GetTreeSideAmount(amount, totalAmount, fee string, sysDecimal, tokenDecimal return amount4Tree, totalAmount4Tree, feeAmount4Tree, nil } -//from向to小数对齐,如果from>to, 需要裁减掉差别部分,且差别部分需要全0,如果fromto, 需要裁减掉差别部分,且差别部分需要全0,如果from 0 && (historyProof.RootHash == reqRootHash || len(reqRootHash) == 0) { @@ -113,7 +113,7 @@ func BuildStateDbHistoryAccount(db dbm.KV, reqRootHash string) (*zt.HistoryAccou return historyAccts, nil } -//BuildHistoryAccountByProof 根据ProofId构建截止到当前proof的account tree,以此账户构建证明,适用于截止到某个proof的证明 +// BuildHistoryAccountByProof 根据ProofId构建截止到当前proof的account tree,以此账户构建证明,适用于截止到某个proof的证明 func BuildHistoryAccountByProof(db dbm.KV, proofId uint64, reqRootHash string, feeAddrs *zt.ZkFeeAddrs) (*zt.HistoryAccountProofInfo, error) { if proofId == 0 { return BuildStateDbHistoryAccount(db, "") @@ -141,7 +141,7 @@ func BuildHistoryAccountByProof(db dbm.KV, proofId uint64, reqRootHash string, f return buildHistoryAccountsByOps(ops, reqRootHash, feeAddrs.EthFeeAddr, feeAddrs.L2FeeAddr) } -//根据某个proof的root恢复所有账户的快照,在资产不会从L2转出到contract时候可以使用 +// 根据某个proof的root恢复所有账户的快照,在资产不会从L2转出到contract时候可以使用 func getHistoryAccountByRoot(localdb dbm.KV, targetRootHash, l1FeeAddr, l2FeeAddr string) (*zt.HistoryAccountProofInfo, error) { info := getHistoryAccountProofFromDb(targetRootHash) if info != nil { @@ -416,7 +416,7 @@ func getAccountMapByOp(op *zt.ZkOperation, accountMap map[uint64]*zt.HistoryLeaf return 0, errors.New(fmt.Sprintf("proxy target token=%d not exist", operation.TokenID)) } else { if tokenBalance.Balance != operation.Amount { - return 0, errors.New(fmt.Sprintf("proxy target tokenBalance different")) + return 0, errors.New("proxy target tokenBalance different") } tokenBalance.Balance = "0" } diff --git a/plugin/dapp/zksync/executor/zkproofutil.go b/plugin/dapp/zksync/executor/zkproofutil.go index ff51208e14..bb0a7e07fd 100644 --- a/plugin/dapp/zksync/executor/zkproofutil.go +++ b/plugin/dapp/zksync/executor/zkproofutil.go @@ -552,7 +552,7 @@ func getTransferNFTOperationByChunk(chunk []byte) *zt.ZkOperation { return &zt.ZkOperation{Ty: zt.TyTransferNFTAction, Op: special} } -//根据ops解析成leaf,并对相同的acctId,tokenId做合并,同时对deposit和withdraw操作做merge +// 根据ops解析成leaf,并对相同的acctId,tokenId做合并,同时对deposit和withdraw操作做merge func parseRollbackOps(ops []*zt.ZkOperation) ([]uint64, []uint64, map[uint64]*zt.HistoryLeaf, map[uint64]*zt.HistoryLeaf, error) { if len(ops) <= 0 { return nil, nil, nil, nil, errors.Wrapf(types.ErrInvalidParam, "rollback ops=0") @@ -620,7 +620,7 @@ func parseRollbackOps(ops []*zt.ZkOperation) ([]uint64, []uint64, map[uint64]*zt return depositAcctIds, withdrawAcctIds, depositAccountMap, withdrawAccountMap, nil } -//deposit和withdraw中相同acctId且相同tokenId的balance做一个合并,方便清算 +// deposit和withdraw中相同acctId且相同tokenId的balance做一个合并,方便清算 func mergeAccountMap(depositMap, withdrawMap map[uint64]*zt.HistoryLeaf) error { for i, w := range withdrawMap { if d, ok := depositMap[i]; ok { @@ -700,7 +700,7 @@ func updateLeaf(tree map[uint64]*zt.HistoryLeaf, accountID, tokenID uint64, amou return leaf } -//统计所有token的gap +// 统计所有token的gap func updateTokenGap(tokenGap map[uint64]string, tokenId uint64, gap string) { v, ok := tokenGap[tokenId] if !ok { diff --git a/plugin/dapp/zksync/executor/zkproofutil_test.go b/plugin/dapp/zksync/executor/zkproofutil_test.go index 7c12392a69..efec98124f 100644 --- a/plugin/dapp/zksync/executor/zkproofutil_test.go +++ b/plugin/dapp/zksync/executor/zkproofutil_test.go @@ -66,7 +66,7 @@ func TestParseRollbackOps(t *testing.T) { } -//测试deposit withdraw merge +// 测试deposit withdraw merge func TestParseRollbackOps2(t *testing.T) { special := &zt.ZkDepositWitnessInfo{ AccountID: 5, diff --git a/plugin/dapp/zksync/executor/zksync.go b/plugin/dapp/zksync/executor/zksync.go index 0e446a5534..8671c2fa83 100644 --- a/plugin/dapp/zksync/executor/zksync.go +++ b/plugin/dapp/zksync/executor/zksync.go @@ -7,9 +7,9 @@ import ( log "github.com/33cn/chain33/common/log/log15" drivers "github.com/33cn/chain33/system/dapp" "github.com/33cn/chain33/types" + "github.com/33cn/plugin/plugin/crypto/legacymimc" zt "github.com/33cn/plugin/plugin/dapp/zksync/types" "github.com/33cn/plugin/plugin/dapp/zksync/wallet" - "github.com/33cn/plugin/plugin/crypto/legacymimc" "github.com/consensys/gnark-crypto/ecc/bn254/twistededwards/eddsa" ) @@ -42,7 +42,7 @@ type zksync struct { drivers.DriverBase } -//NewExchange ... +// NewExchange ... func NewZksync() drivers.Driver { t := &zksync{} t.SetChild(t) @@ -55,7 +55,7 @@ func GetName() string { return NewZksync().GetName() } -//GetDriverName ... +// GetDriverName ... func (z *zksync) GetDriverName() string { return driverName } @@ -129,7 +129,7 @@ func (z *zksync) CheckTx(tx *types.Transaction, index int) error { return nil } -//ExecutorOrder Exec 的时候 同时执行 ExecLocal +// ExecutorOrder Exec 的时候 同时执行 ExecLocal func (z *zksync) ExecutorOrder() int64 { return drivers.ExecLocalSameTime } diff --git a/plugin/dapp/zksync/executor/zksyncOption.go b/plugin/dapp/zksync/executor/zksyncOption.go index 568fe0872f..e3c4c26e99 100644 --- a/plugin/dapp/zksync/executor/zksyncOption.go +++ b/plugin/dapp/zksync/executor/zksyncOption.go @@ -14,8 +14,8 @@ import ( dbm "github.com/33cn/chain33/common/db" "github.com/33cn/chain33/system/dapp" "github.com/33cn/chain33/types" - zt "github.com/33cn/plugin/plugin/dapp/zksync/types" "github.com/33cn/plugin/plugin/crypto/legacymimc" + zt "github.com/33cn/plugin/plugin/dapp/zksync/types" "github.com/pkg/errors" ) @@ -36,7 +36,7 @@ type Action struct { api client.QueueProtocolAPI } -//NewAction ... +// NewAction ... func NewAction(z *zksync, tx *types.Transaction, index int) *Action { hash := tx.Hash() fromaddr := tx.From() @@ -53,12 +53,12 @@ func NewAction(z *zksync, tx *types.Transaction, index int) *Action { } } -//GetIndex get index +// GetIndex get index func (a *Action) GetIndex() int64 { return a.height*types.MaxTxsPerBlock + int64(a.index) } -//TODO:HexAddr2Decimal 地址的转换在确认其必要性,最后在合约内部进行清理, +// TODO:HexAddr2Decimal 地址的转换在确认其必要性,最后在合约内部进行清理, func (a *Action) Deposit(payload *zt.ZkDeposit) (*types.Receipt, error) { var logs []*types.ReceiptLog var kvs []*types.KeyValue @@ -184,7 +184,7 @@ func (a *Action) Deposit(payload *zt.ZkDeposit) (*types.Receipt, error) { return receipts, nil } -//L2 queue id 从1开始编号,跟L1 priority 不同,后者为了和eth合约编号保持一致 +// L2 queue id 从1开始编号,跟L1 priority 不同,后者为了和eth合约编号保持一致 func setL2QueueData(db dbm.KV, ops []*zt.ZkOperation) (*types.Receipt, int64, error) { receipts := &types.Receipt{Ty: types.ExecOk} //add deposit queue @@ -359,9 +359,9 @@ func (a *Action) ContractToTree(payload *zt.ZkContractToTree) (*types.Receipt, e return a.contractToTreeNewProc(payload, token) } -//合约----> L2账户操作, -//SystemTree2ContractAcctId ----> 目的账户 -//在合约上销毁等量的余额 +// 合约----> L2账户操作, +// SystemTree2ContractAcctId ----> 目的账户 +// 在合约上销毁等量的余额 func (a *Action) contractToTreeAcctIdProc(payload *zt.ZkContractToTree, token *zt.ZkTokenSymbol) (*types.Receipt, error) { tokenIdBigint, _ := new(big.Int).SetString(token.Id, 10) tokenId := tokenIdBigint.Uint64() @@ -486,9 +486,9 @@ func (a *Action) contractToTreeNewProc(payload *zt.ZkContractToTree, token *zt.Z return receipts, nil } -//L2 ----> 合约账户(树) -//操作1. FromAccountId -----> SystemTree2ContractAcctId,执行ZkTransfer -//操作2. UpdateContractAccount,在合约内部的铸币操作 +// L2 ----> 合约账户(树) +// 操作1. FromAccountId -----> SystemTree2ContractAcctId,执行ZkTransfer +// 操作2. UpdateContractAccount,在合约内部的铸币操作 func (a *Action) TreeToContract(payload *zt.ZkTreeToContract) (*types.Receipt, error) { err := checkParam(payload.Amount) if nil != err { @@ -587,7 +587,7 @@ func (a *Action) UpdateContractAccount(amount, symbol string, option int32, exec return &execReceipt, nil } -//trasfer, tree2contract, contract2tree 本质都是transfer,这里共用一个transferProc +// trasfer, tree2contract, contract2tree 本质都是transfer,这里共用一个transferProc func (a *Action) l2TransferProc(payload *zt.ZkTransfer, actionTy int32, decimal int) (*types.Receipt, error) { var logs []*types.ReceiptLog var kvs []*types.KeyValue @@ -750,7 +750,7 @@ func (a *Action) transferToNewProcess(accountIdFrom uint64, toChain33Address, to return a.transferToNewInnerProcess(fromLeaf, toChain33Address, toEthAddress, totalAmount, amount, tokenID) } -//contract2tree 也支持tree上新创建账户id, 和transfer2new共用 +// contract2tree 也支持tree上新创建账户id, 和transfer2new共用 func (a *Action) transferToNewInnerProcess(fromLeaf *zt.Leaf, toChain33Address, toEthAddress, totalAmount, amount string, tokenID uint64) (*types.Receipt, uint64, error) { var kvs []*types.KeyValue var logs []*types.ReceiptLog @@ -1072,7 +1072,7 @@ func (a *Action) SetDefultPubKey(payload *zt.ZkSetPubKey) ([]*types.KeyValue, [] return kvs, localKvs, nil } -//设置代理地址的公钥 +// 设置代理地址的公钥 func (a *Action) SetProxyPubKey(payload *zt.ZkSetPubKey, leaf *zt.Leaf) ([]*types.KeyValue, []*types.KeyValue, error) { err := authVerification(payload.Signature.PubKey, leaf.PubKey) @@ -1161,7 +1161,7 @@ func (a *Action) SetProxyPubKey(payload *zt.ZkSetPubKey, leaf *zt.Leaf) ([]*type // return mergeReceipt(receipts, r), nil //} -//验证身份 +// 验证身份 func authVerification(signPubKey *zt.ZkPubKey, leafPubKey *zt.ZkPubKey) error { if signPubKey == nil || leafPubKey == nil { return errors.New("set your pubKey") @@ -1172,7 +1172,7 @@ func authVerification(signPubKey *zt.ZkPubKey, leafPubKey *zt.ZkPubKey) error { return nil } -//检查参数 +// 检查参数 func checkParam(amount string) error { if amount == "" || strings.HasPrefix(amount, "-") { return types.ErrAmount @@ -1187,7 +1187,7 @@ func checkParam(amount string) error { return nil } -//not NFT token +// not NFT token func checkIsNormalToken(id uint64) bool { return id < zt.SystemNFTTokenId } @@ -1458,7 +1458,7 @@ func getDbFeeData(db dbm.KV, actionTy int32, tokenId uint64) (string, error) { return string(v), nil } -//该接口需要被zkrelayer使用 +// 该接口需要被zkrelayer使用 func GetFeeData(db dbm.KV, actionTy int32, tokenId uint64) (*zt.ZkFee, error) { //缺省输入的tokenId,如果swapFee有输入新tokenId,采用新的,在withdraw等action忽略swapFee tokenId feeInfo := &zt.ZkFee{ @@ -1721,7 +1721,7 @@ func (a *Action) MintNFT(payload *zt.ZkMintNFT) (*types.Receipt, error) { return receipts, nil } -//计数新NFT Id的balance 参数hash作为其balance,不可变 +// 计数新NFT Id的balance 参数hash作为其balance,不可变 func getNewNFTTokenBalance(creatorId uint64, creatorSerialId string, protocol, amount uint64, contentHashPart1, contentHashPart2 string) (string, error) { hashFn := legacymimc.NewMiMC(zt.ZkMimcHashSeed) hashFn.Reset() @@ -2018,10 +2018,10 @@ func makeSetExodusModeReceipt(prev, current int64) *types.Receipt { } } -//在设置了invalidTx后,平行链从0开始同步到无效交易则设置系统为exodus mode,此模式意味着此链即将停用,资产需要退出到ETH -//目前此模式限制交易比较多,此模式开启后的后续所有跟L2 资产有关的交易(contract2tree例外)都视为无效交易,其中deposit,withdraw,proxyExit确实应该视为无效 -//但是transfer,transfer2new, tree2contract实际上应该是允许的,因为只是在L2内部流转, 禁掉的影响是跟这几个操作相关连的交易会失败 -//改进的一个方案是允许这几个操作,但是需要重新设一个截止标志,禁止这几个操作,也就是平行链同步完成后,由管理员设置,然后就只允许contract2tree流进资产 +// 在设置了invalidTx后,平行链从0开始同步到无效交易则设置系统为exodus mode,此模式意味着此链即将停用,资产需要退出到ETH +// 目前此模式限制交易比较多,此模式开启后的后续所有跟L2 资产有关的交易(contract2tree例外)都视为无效交易,其中deposit,withdraw,proxyExit确实应该视为无效 +// 但是transfer,transfer2new, tree2contract实际上应该是允许的,因为只是在L2内部流转, 禁掉的影响是跟这几个操作相关连的交易会失败 +// 改进的一个方案是允许这几个操作,但是需要重新设一个截止标志,禁止这几个操作,也就是平行链同步完成后,由管理员设置,然后就只允许contract2tree流进资产 func isExodusMode(statedb dbm.KV) error { mode, err := getExodusMode(statedb) if err != nil { @@ -2050,7 +2050,7 @@ func getExodusMode(db dbm.KV) (int64, error) { return k.Data, nil } -//设置逃生舱模式,为保证顺序,管理员只允许在无效交易生效后,也就是逃生舱准备模式后设置清算模式 +// 设置逃生舱模式,为保证顺序,管理员只允许在无效交易生效后,也就是逃生舱准备模式后设置清算模式 func (a *Action) setExodusMode(payload *zt.ZkExodusMode) (*types.Receipt, error) { cfg := a.api.GetConfig() if payload.GetMode() < zt.NormalMode || payload.GetMode() > zt.ExodusFinalMode { @@ -2169,7 +2169,7 @@ func (a *Action) procExodusRollbackMode(payload *zt.ZkExodusMode) (*types.Receip } -//获取deposit操作需要回滚的数据,如果余额不够,尝试从systemFeeId扣除,如果fee也不够,记录gap从L1补充 +// 获取deposit操作需要回滚的数据,如果余额不够,尝试从systemFeeId扣除,如果fee也不够,记录gap从L1补充 func getDepositRollbackData(db dbm.KV, depositAcctIds []uint64, depositAccountMap map[uint64]*zt.HistoryLeaf, knownBalanceGap uint32) ([]*zt.ZkAcctRollbackInfo, error) { var depositRollbackAcctData []*zt.ZkAcctRollbackInfo tokensGap := make(map[uint64]string) @@ -2261,7 +2261,7 @@ func checkSystemFeeAcctGap(sysFeeTokens, tokensGap map[uint64]string) ([]*zt.ZkA var systemGapResp string var systemGapData []*zt.ZkAcctRollbackInfo var tokenIds []uint64 //记录顺序 - for id, _ := range tokensGap { + for id := range tokensGap { tokenIds = append(tokenIds, id) } sort.Slice(tokenIds, func(i, j int) bool { return tokenIds[i] < tokenIds[j] }) @@ -2404,7 +2404,7 @@ func MakeSetTokenSymbolReceipt(id string, oldVal, newVal *zt.ZkTokenSymbol) *typ } } -//tokenId可以对应多个symbol,但一个symbol只能对应一个Id,比如Id=1,symbol=USTC,后改成USTD, USTC仍然会对应Id=1, 新的Id不能使用已存在的名字,防止重复混乱 +// tokenId可以对应多个symbol,但一个symbol只能对应一个Id,比如Id=1,symbol=USTC,后改成USTD, USTC仍然会对应Id=1, 新的Id不能使用已存在的名字,防止重复混乱 func (a *Action) setTokenSymbol(payload *zt.ZkTokenSymbol) (*types.Receipt, error) { cfg := a.api.GetConfig() diff --git a/plugin/dapp/zksync/types/witness.pb.go b/plugin/dapp/zksync/types/witness.pb.go index 1b8263e2f3..6d0f098c0b 100644 --- a/plugin/dapp/zksync/types/witness.pb.go +++ b/plugin/dapp/zksync/types/witness.pb.go @@ -479,7 +479,7 @@ func (x *TokenWitness) GetSibling() *SiblingPath { return nil } -//one operation branch +// one operation branch type OperationMetaBranch struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -933,7 +933,7 @@ func (x *ZkFee) GetTokenID() uint64 { return 0 } -//optional, 记录operation的queue对应的tx的block height和txIndex,方便定位 +// optional, 记录operation的queue对应的tx的block height和txIndex,方便定位 type OpBlockInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1758,7 +1758,7 @@ func (x *ZkContractToTreeWitnessInfo) GetBlockInfo() *OpBlockInfo { return nil } -//直接产生新的tree地址 +// 直接产生新的tree地址 type ZkContractToTreeNewWitnessInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/zksync/types/zksync.go b/plugin/dapp/zksync/types/zksync.go index 4cbbe3d486..c3a835c56a 100644 --- a/plugin/dapp/zksync/types/zksync.go +++ b/plugin/dapp/zksync/types/zksync.go @@ -130,17 +130,17 @@ const ( MinDecimalAllow = 4 ) -//Zksync 执行器名称定义 +// Zksync 执行器名称定义 const Zksync = "zksync" const ZkManagerKey = "manager" const ZkMimcHashSeed = "seed" const ZkVerifierKey = "verifier" -//配置的系统收交易费账户 +// 配置的系统收交易费账户 const ZkCfgEthFeeAddr = "ethFeeAddr" const ZkCfgLayer2FeeAddr = "layer2FeeAddr" -//msg宽度 +// msg宽度 const ( TxTypeBitWidth = 8 //1byte AccountBitWidth = 32 //4byte @@ -169,7 +169,7 @@ const ( ) -//不同type chunk数量 +// 不同type chunk数量 const ( DepositChunks = 3 Contract2TreeChunks = 2 @@ -204,7 +204,7 @@ const ( ) -//ERC protocol +// ERC protocol const ( ZKERC1155 = 1 ZKERC721 = 2 @@ -326,12 +326,12 @@ func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(Zksync, NewType(cfg)) } -//ZksyncType ... +// ZksyncType ... type ZksyncType struct { types.ExecTypeBase } -//NewType ... +// NewType ... func NewType(cfg *types.Chain33Config) *ZksyncType { c := &ZksyncType{} c.SetChild(c) diff --git a/plugin/dapp/zksync/types/zksync.pb.go b/plugin/dapp/zksync/types/zksync.pb.go index 281ac93828..f2937138ff 100644 --- a/plugin/dapp/zksync/types/zksync.pb.go +++ b/plugin/dapp/zksync/types/zksync.pb.go @@ -455,7 +455,7 @@ func (x *ZkTokenSymbol) GetDecimal() uint32 { return 0 } -//某个token的余额 +// 某个token的余额 type TokenBalance struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1072,7 +1072,7 @@ func (x *ZkWithdraw) GetSignature() *ZkSignature { return nil } -//从chain33合约提款到二层 +// 从chain33合约提款到二层 type ZkContractToTree struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -1168,7 +1168,7 @@ func (x *ZkContractToTree) GetFromExec() string { return "" } -//从二层铸造到chain33合约 +// 从二层铸造到chain33合约 type ZkTreeToContract struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2093,7 +2093,7 @@ func (x *ZkNFTTokenStatus) GetBurnedAmount() uint64 { return 0 } -//电路验证key +// 电路验证key type ZkVerifyKey struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2251,7 +2251,7 @@ func (x *ZkFeeAddrs) GetL2FeeAddr() string { return "" } -//commit proof tx data +// commit proof tx data type ZkCommitProof struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2407,7 +2407,7 @@ func (x *ZkCommitProof) GetCommitBlockHeight() int64 { return 0 } -//commit proof stat, pubdata保存到localdb +// commit proof stat, pubdata保存到localdb type CommitProofState struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2711,7 +2711,7 @@ func (x *QueryProofInfo) GetQueues() *ProofId2QueueIdData { return nil } -//电路验证者名单 +// 电路验证者名单 type ZkVerifier struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2948,7 +2948,7 @@ func (x *ReceiptSetFee) GetCurrentAmount() string { return "" } -//zk relayer operators +// zk relayer operators type RelayerOperators struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -3375,7 +3375,7 @@ func (x *ZkQueryProofResp) GetOperationInfos() []*OperationInfo { return nil } -//query committed proof info +// query committed proof info type ZkFetchProofList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -3455,7 +3455,7 @@ func (x *ZkFetchProofList) GetEndHeight() uint64 { return 0 } -//NFT content hash切分成两部分 +// NFT content hash切分成两部分 type ZkContentHash struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -3606,7 +3606,7 @@ func (x *ZkOpNFTData) GetContent() *ZkContentHash { return nil } -//swapData: from maker pov +// swapData: from maker pov type ZkOpSwapData struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -4677,7 +4677,7 @@ func (x *ZkExodusBatchProofReq) GetRootHash() string { return "" } -//记录L2 的所有operation 到queue,以和proof校验 +// 记录L2 的所有operation 到queue,以和proof校验 type ReceiptL2LastQueueID struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/plugin/dapp/zksync/wallet/utils.go b/plugin/dapp/zksync/wallet/utils.go index 861c5e1bd5..d7d4cad2b7 100644 --- a/plugin/dapp/zksync/wallet/utils.go +++ b/plugin/dapp/zksync/wallet/utils.go @@ -11,9 +11,9 @@ import ( "github.com/pkg/errors" "github.com/33cn/chain33/types" + "github.com/33cn/plugin/plugin/crypto/legacymimc" zt "github.com/33cn/plugin/plugin/dapp/zksync/types" "github.com/consensys/gnark-crypto/ecc/bn254/fr" - "github.com/33cn/plugin/plugin/crypto/legacymimc" ) func CreateRawTx(actionTy int32, tokenId uint64, amount string, toEthAddress string, @@ -65,7 +65,7 @@ func CreateRawTx(actionTy int32, tokenId uint64, amount string, toEthAddress str return payload, nil } -//11 => 00001011, 数组index0值为0,大端表示 +// 11 => 00001011, 数组index0值为0,大端表示 func getBigEndBitsWithFixLen(val *big.Int, n uint64) []uint { l := val.BitLen() if n < uint64(l) { @@ -87,7 +87,7 @@ func getBigEndBitsWithFixLen(val *big.Int, n uint64) []uint { return bits } -//把bits以小端模式构建big.Int +// 把bits以小端模式构建big.Int func setBeBitsToVal(bits []uint) string { a := big.NewInt(0) for i := 0; i < len(bits); i++ { @@ -342,7 +342,7 @@ func GetMintNFTMsg(payload *zt.ZkMintNFT) *zt.ZkMsg { part1, part2, _, err := zt.SplitNFTContent(payload.ContentHash) if err != nil { - fmt.Println(fmt.Sprintf("split content hash=%s wrong", payload.ContentHash)) + fmt.Printf("split content hash=%s wrong\n", payload.ContentHash) panic(err) } @@ -411,9 +411,9 @@ func GetMsgHash(msg *zt.ZkMsg) []byte { return hash.Sum(nil) } -//GetLayer2PrivateKeySeed 通过用户secp256k1私钥对特定信息的签名的hash产生layer2的eddsa签名的私钥种子来产生用户layer2的私钥 -//在memtamask或钱包app可以不暴露用户私钥而只是内部签名的方式来产生layer2私钥,更加安全 -//refer to https://blogs.loopring.org/new-approach-to-generating-layer-2-account-keys-cn/ +// GetLayer2PrivateKeySeed 通过用户secp256k1私钥对特定信息的签名的hash产生layer2的eddsa签名的私钥种子来产生用户layer2的私钥 +// 在memtamask或钱包app可以不暴露用户私钥而只是内部签名的方式来产生layer2私钥,更加安全 +// refer to https://blogs.loopring.org/new-approach-to-generating-layer-2-account-keys-cn/ func GetLayer2PrivateKeySeed(privateKey, exchangeAddr, nonce string) ([]byte, error) { c, err := crypto.Load(secp256k1.Name, -1) if err != nil { diff --git a/plugin/mempool/para/base.go b/plugin/mempool/para/base.go index b3fa28ae38..db8acd3a01 100644 --- a/plugin/mempool/para/base.go +++ b/plugin/mempool/para/base.go @@ -15,7 +15,7 @@ import ( var mlog = log.New("module", "mempool.para") var topic = "mempool" -//Mempool mempool 基础类 +// Mempool mempool 基础类 type Mempool struct { key string wg sync.WaitGroup @@ -25,14 +25,14 @@ type Mempool struct { isclose int32 } -//NewMempool 新建mempool 实例 +// NewMempool 新建mempool 实例 func NewMempool(cfg *types.Mempool) *Mempool { pool := &Mempool{} pool.key = topic return pool } -//SetQueueClient 初始化mempool模块 +// SetQueueClient 初始化mempool模块 func (mem *Mempool) SetQueueClient(client queue.Client) { mem.client = client mem.client.Sub(mem.key) diff --git a/plugin/mempool/para/mempool.go b/plugin/mempool/para/mempool.go index 66bff36e2c..e2ad1eccce 100644 --- a/plugin/mempool/para/mempool.go +++ b/plugin/mempool/para/mempool.go @@ -13,7 +13,7 @@ func init() { drivers.Reg("para", New) } -//New 创建price cache 结构的 mempool +// New 创建price cache 结构的 mempool func New(cfg *types.Mempool, sub []byte) queue.Module { return NewMempool(cfg) } diff --git a/plugin/mempool/price/cache.go b/plugin/mempool/price/cache.go index 44ab0e2dca..d6fe69737c 100644 --- a/plugin/mempool/price/cache.go +++ b/plugin/mempool/price/cache.go @@ -49,7 +49,7 @@ func NewQueue(subcfg subConfig) *Queue { } } -//GetItem 获取数据通过 key +// GetItem 获取数据通过 key func (cache *Queue) GetItem(hash string) (*mempool.Item, error) { item, err := cache.Queue.GetItem(hash) if err != nil { @@ -58,12 +58,12 @@ func (cache *Queue) GetItem(hash string) (*mempool.Item, error) { return item.(*priceScore).Item, nil } -//Push 加入数据到队列 +// Push 加入数据到队列 func (cache *Queue) Push(item *mempool.Item) error { return cache.Queue.Push(&priceScore{Item: item}) } -//Walk 获取数据通过 key +// Walk 获取数据通过 key func (cache *Queue) Walk(count int, cb func(tx *mempool.Item) bool) { cache.Queue.Walk(count, func(item skiplist.Scorer) bool { return cb(item.(*priceScore).Item) diff --git a/plugin/mempool/price/mempool.go b/plugin/mempool/price/mempool.go index 2ac63c755e..3a1b907dee 100644 --- a/plugin/mempool/price/mempool.go +++ b/plugin/mempool/price/mempool.go @@ -18,7 +18,7 @@ func init() { drivers.Reg("price", New) } -//New 创建price cache 结构的 mempool +// New 创建price cache 结构的 mempool func New(cfg *types.Mempool, sub []byte) queue.Module { c := drivers.NewMempool(cfg) var subcfg subConfig diff --git a/plugin/mempool/score/cache.go b/plugin/mempool/score/cache.go index d4bce3d64b..7f52470a05 100644 --- a/plugin/mempool/score/cache.go +++ b/plugin/mempool/score/cache.go @@ -60,7 +60,7 @@ func NewQueue(subcfg subConfig) *Queue { // cache.subConfig.PricePower - cache.subConfig.TimeParam*item.EnterTime, Value: item}, nil //} -//GetItem 获取数据通过 key +// GetItem 获取数据通过 key func (cache *Queue) GetItem(hash string) (*mempool.Item, error) { item, err := cache.Queue.GetItem(hash) if err != nil { diff --git a/plugin/mempool/score/mempool.go b/plugin/mempool/score/mempool.go index b44e66dcde..8b67d68f99 100644 --- a/plugin/mempool/score/mempool.go +++ b/plugin/mempool/score/mempool.go @@ -21,7 +21,7 @@ func init() { drivers.Reg("score", New) } -//New 创建score cache 结构的 mempool +// New 创建score cache 结构的 mempool func New(cfg *types.Mempool, sub []byte) queue.Module { c := drivers.NewMempool(cfg) var subcfg subConfig diff --git a/plugin/p2p/gossip/addrbook.go b/plugin/p2p/gossip/addrbook.go index 89f8813c62..2c142a4524 100644 --- a/plugin/p2p/gossip/addrbook.go +++ b/plugin/p2p/gossip/addrbook.go @@ -323,9 +323,7 @@ func (a *AddrBook) AddAddress(addr *NetAddress, ka *KnownAddress) { func (a *AddrBook) RemoveAddr(peeraddr string) { a.mtx.Lock() defer a.mtx.Unlock() - if _, ok := a.addrPeer[peeraddr]; ok { - delete(a.addrPeer, peeraddr) - } + delete(a.addrPeer, peeraddr) } // GetPeers return peerlist @@ -362,7 +360,7 @@ func (a *AddrBook) initKey() { return } } - panic(fmt.Sprintf("p2p initPrivPubkey failed")) + panic("p2p initPrivPubkey failed") } @@ -374,7 +372,7 @@ func (a *AddrBook) setKey(privkey, pubkey string) { } -//ResetPeerkey reset priv,pub key +// ResetPeerkey reset priv,pub key func (a *AddrBook) ResetPeerkey(privkey, pubkey string) { if privkey == "" || pubkey == "" { diff --git a/plugin/p2p/gossip/common.go b/plugin/p2p/gossip/common.go index b7d56ddeb6..f901c6900e 100644 --- a/plugin/p2p/gossip/common.go +++ b/plugin/p2p/gossip/common.go @@ -29,7 +29,7 @@ var P2pComm Comm // Comm information type Comm struct{} -//CheckNetAddr check addr or ip format +// CheckNetAddr check addr or ip format func (Comm) ParaseNetAddr(addr string) (string, int64, error) { //check peerAddr if !strings.Contains(addr, ":") { //only ip @@ -152,7 +152,7 @@ func (c Comm) dialPeerWithAddress(addr *NetAddress, persistent bool, node *Node) log.Info("dialPeerWithAddress", "duplicate connect:", prepeer.Addr(), addr.String(), resp.GetUserAgent()) } peer.Close() - return nil, errors.New(fmt.Sprintf("duplicate connect %v", resp.UserAgent)) + return nil, fmt.Errorf("duplicate connect %v", resp.UserAgent) } node.peerStore.Store(addr.String(), resp.UserAgent) peer.SetPeerName(resp.UserAgent) diff --git a/plugin/p2p/gossip/const.go b/plugin/p2p/gossip/const.go index 13a39702cd..5d2d2d3175 100644 --- a/plugin/p2p/gossip/const.go +++ b/plugin/p2p/gossip/const.go @@ -61,7 +61,7 @@ const ( privKeyTag = "privkey" ) -//TTL +// TTL const ( DefaultLtTxBroadCastTTL = 3 DefaultMaxTxBroadCastTTL = 25 diff --git a/plugin/p2p/gossip/downloadblocks.go b/plugin/p2p/gossip/downloadblocks.go index c463db1b60..8d7cbc5859 100644 --- a/plugin/p2p/gossip/downloadblocks.go +++ b/plugin/p2p/gossip/downloadblocks.go @@ -20,17 +20,17 @@ import ( // Invs datastruct type Invs []*pb.Inventory -//Len size of the Invs data +// Len size of the Invs data func (i Invs) Len() int { return len(i) } -//Less Sort from low to high +// Less Sort from low to high func (i Invs) Less(a, b int) bool { return i[a].GetHeight() < i[b].GetHeight() } -//Swap the param +// Swap the param func (i Invs) Swap(a, b int) { i[a], i[b] = i[b], i[a] } @@ -145,7 +145,7 @@ func (d *DownloadJob) setFreePeer(pid string) { } } -//加入到重试数组 +// 加入到重试数组 func (d *DownloadJob) appendRetryItem(item *pb.Inventory) { d.mtx.Lock() defer d.mtx.Unlock() diff --git a/plugin/p2p/gossip/monitor.go b/plugin/p2p/gossip/monitor.go index 980c25d56c..a5622a9842 100644 --- a/plugin/p2p/gossip/monitor.go +++ b/plugin/p2p/gossip/monitor.go @@ -613,49 +613,45 @@ func (n *Node) monitorCerts() { return } - for { - select { - case <-ticker.C: - //check serialNum - var resp []string - var s struct { - Serials []string `json:"serials,omitempty"` - } - s.Serials = getSerialNums() - if len(s.Serials) == 0 { - continue - } - log.Debug("check cert serialNum++++++", "certNum.", len(s.Serials)) - err = jcli.Call("Validate", s, &resp) - if err != nil { - log.Error("monitorCerts", "rpc call err", err) - continue - } + for range ticker.C { + //check serialNum + var resp []string + var s struct { + Serials []string `json:"serials,omitempty"` + } + s.Serials = getSerialNums() + if len(s.Serials) == 0 { + continue + } + log.Debug("check cert serialNum++++++", "certNum.", len(s.Serials)) + err = jcli.Call("Validate", s, &resp) + if err != nil { + log.Error("monitorCerts", "rpc call err", err) + continue + } - log.Debug("monitorCerts", "resp", resp) - tempCerts := getSerials() - for _, serialNum := range resp { - //设置证书序列号状态 - certinfo := updateCertSerial(serialNum, true) - delete(tempCerts, serialNum) - for pname, peer := range n.nodeInfo.peerInfos.GetPeerInfos() { - if peer.GetAddr() == certinfo.ip { - v, ok := latestSerials.Load(certinfo.ip) - if ok && v.(string) == serialNum { - n.remove(pname) //断开已经连接的节点 - } + log.Debug("monitorCerts", "resp", resp) + tempCerts := getSerials() + for _, serialNum := range resp { + //设置证书序列号状态 + certinfo := updateCertSerial(serialNum, true) + delete(tempCerts, serialNum) + for pname, peer := range n.nodeInfo.peerInfos.GetPeerInfos() { + if peer.GetAddr() == certinfo.ip { + v, ok := latestSerials.Load(certinfo.ip) + if ok && v.(string) == serialNum { + n.remove(pname) //断开已经连接的节点 } } } - log.Debug("monitorCert", "tempCerts", tempCerts) - //处理解除吊销的节点 - for serialNum, info := range tempCerts { - if info.revoke { - // 被撤销的证书恢复正常 - updateCertSerial(serialNum, !info.revoke) - } + } + log.Debug("monitorCert", "tempCerts", tempCerts) + //处理解除吊销的节点 + for serialNum, info := range tempCerts { + if info.revoke { + // 被撤销的证书恢复正常 + updateCertSerial(serialNum, !info.revoke) } - } } diff --git a/plugin/p2p/gossip/nat/nat.go b/plugin/p2p/gossip/nat/nat.go index 0e0d4fcd6e..274b48bcb1 100644 --- a/plugin/p2p/gossip/nat/nat.go +++ b/plugin/p2p/gossip/nat/nat.go @@ -62,12 +62,12 @@ type Interface interface { // The following formats are currently accepted. // Note that mechanism names are not case-sensitive. // -// "" or "none" return nil -// "extip:77.12.33.4" will assume the local machine is reachable on the given IP -// "any" uses the first auto-detected mechanism -// "upnp" uses the Universal Plug and Play protocol -// "pmp" uses NAT-PMP with an auto-detected gateway address -// "pmp:192.168.0.1" uses NAT-PMP with the given gateway address +// "" or "none" return nil +// "extip:77.12.33.4" will assume the local machine is reachable on the given IP +// "any" uses the first auto-detected mechanism +// "upnp" uses the Universal Plug and Play protocol +// "pmp" uses NAT-PMP with an auto-detected gateway address +// "pmp:192.168.0.1" uses NAT-PMP with the given gateway address func Parse(spec string) (Interface, error) { var ( parts = strings.SplitN(spec, ":", 2) diff --git a/plugin/p2p/gossip/node.go b/plugin/p2p/gossip/node.go index 3caebba00c..69809a193f 100644 --- a/plugin/p2p/gossip/node.go +++ b/plugin/p2p/gossip/node.go @@ -578,7 +578,7 @@ func (n *Node) verifyP2PChannel(channel int32) bool { return channel == n.nodeInfo.cfg.Channel } -//检测该节点地址是否作为客户端连入, 此时需要维护双向连接, 增加了节点间的连接冗余 +// 检测该节点地址是否作为客户端连入, 此时需要维护双向连接, 增加了节点间的连接冗余 func (n *Node) isInBoundPeer(peerName string) (bool, *innerpeer) { if n.server == nil || n.server.p2pserver == nil { diff --git a/plugin/p2p/gossip/p2p.go b/plugin/p2p/gossip/p2p.go index ed6c56866b..adbd8520b3 100644 --- a/plugin/p2p/gossip/p2p.go +++ b/plugin/p2p/gossip/p2p.go @@ -140,7 +140,7 @@ func New(mgr *p2p.Manager, subCfg []byte) p2p.IP2P { return p2p } -//Wait wait for ready +// Wait wait for ready func (network *P2p) Wait() {} func (network *P2p) isClose() bool { @@ -151,7 +151,7 @@ func (network *P2p) isRestart() bool { return atomic.LoadInt32(&network.restart) == 1 } -//CloseP2P Close network client +// CloseP2P Close network client func (network *P2p) CloseP2P() { network.lock.Lock() defer network.lock.Unlock() @@ -327,7 +327,7 @@ func (network *P2p) genAirDropKeyFromWallet() error { return nil } -//ReStart p2p +// ReStart p2p func (network *P2p) ReStart() { network.lock.Lock() defer network.lock.Unlock() diff --git a/plugin/p2p/gossip/p2p_test.go b/plugin/p2p/gossip/p2p_test.go index df1a2bf43d..8fc28877ed 100644 --- a/plugin/p2p/gossip/p2p_test.go +++ b/plugin/p2p/gossip/p2p_test.go @@ -125,7 +125,7 @@ func processMsg(q queue.Queue) { }() } -//new p2p +// new p2p func newP2p(cfg *types.Chain33Config, port int32, dbpath string, q queue.Queue) *P2p { p2pCfg := cfg.GetModuleConfig().P2P p2pCfg.Enable = true @@ -152,7 +152,7 @@ func newP2p(cfg *types.Chain33Config, port int32, dbpath string, q queue.Queue) return p2pcli } -//free P2p +// free P2p func freeP2p(p2p *P2p) { p2p.CloseP2P() if err := os.RemoveAll(p2p.p2pCfg.DbPath); err != nil { @@ -187,7 +187,7 @@ func testNetInfo(t *testing.T, p2p *P2p) { assert.NotNil(t, p2p.node.nodeInfo.GetExternalAddr()) } -//测试Peer +// 测试Peer func testPeer(t *testing.T, p2p *P2p, q queue.Queue) { cfg := types.NewChain33Config(types.ReadFile("../../../chain33.toml")) conn, err := grpc.Dial("localhost:53802", grpc.WithInsecure(), @@ -310,7 +310,7 @@ func testPeer(t *testing.T, p2p *P2p, q queue.Queue) { localP2P.node.remove(peer.GetPeerName()) } -//测试grpc 多连接 +// 测试grpc 多连接 func testGrpcConns(t *testing.T) { var conns []*grpc.ClientConn @@ -341,7 +341,7 @@ func testGrpcConns(t *testing.T) { } -//测试grpc 流多连接 +// 测试grpc 流多连接 func testGrpcStreamConns(t *testing.T, p2p *P2p) { conn, err := grpc.Dial("localhost:53802", grpc.WithInsecure(), diff --git a/plugin/p2p/gossip/p2pserver.go b/plugin/p2p/gossip/p2pserver.go index 7c40c3f351..1ca5fe0d14 100644 --- a/plugin/p2p/gossip/p2pserver.go +++ b/plugin/p2p/gossip/p2pserver.go @@ -632,7 +632,7 @@ func (s *P2pserver) addStreamHandler(peerName string) chan interface{} { return s.streams[peerName] } -//发布数据到所有服务流 +// 发布数据到所有服务流 func (s *P2pserver) pubToAllStream(data interface{}) { s.smtx.Lock() defer s.smtx.Unlock() @@ -648,7 +648,7 @@ func (s *P2pserver) pubToAllStream(data interface{}) { } } -//发布数据到指定流 +// 发布数据到指定流 func (s *P2pserver) pubToStream(data interface{}, peerName string) { s.smtx.Lock() defer s.smtx.Unlock() diff --git a/plugin/p2p/gossip/process.go b/plugin/p2p/gossip/process.go index 0915cd38e9..2105861457 100644 --- a/plugin/p2p/gossip/process.go +++ b/plugin/p2p/gossip/process.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//Package gossip ... +// Package gossip ... package gossip import ( @@ -470,7 +470,7 @@ func (n *Node) postMempool(txHash string, tx *types.Transaction) error { return err } -//检测是否冗余发送, 或者添加到发送过滤(内部存在直接修改读写保护的数据, 对filter lru的读写需要外层锁保护) +// 检测是否冗余发送, 或者添加到发送过滤(内部存在直接修改读写保护的数据, 对filter lru的读写需要外层锁保护) func (n *Node) addIgnoreSendPeerAtomic(filter *utils.Filterdata, key, pid string) (exist bool) { filter.GetAtomicLock() diff --git a/plugin/p2p/gossip/tls.go b/plugin/p2p/gossip/tls.go index 2662075e5b..1ac77a6666 100644 --- a/plugin/p2p/gossip/tls.go +++ b/plugin/p2p/gossip/tls.go @@ -4,7 +4,6 @@ import ( "context" "crypto/tls" "crypto/x509" - "errors" "fmt" "net" "net/url" @@ -15,7 +14,7 @@ import ( "google.golang.org/grpc/credentials" ) -//Tls defines the specific interface for all the live gRPC wire +// Tls defines the specific interface for all the live gRPC wire // protocols and supported transport security protocols (e.g., TLS, SSL). type Tls struct { config *tls.Config @@ -33,7 +32,7 @@ var ( latestSerials sync.Map ) -//serialNum -->ip +// serialNum -->ip func addCertSerial(serial string, ip string) { revokeLock.Lock() defer revokeLock.Unlock() @@ -146,7 +145,7 @@ func (c *Tls) ClientHandshake(ctx context.Context, authority string, rawConn net //检查证书是否被吊销 if isRevoke(peerSerialNum.String()) { conn.Close() - return nil, nil, errors.New(fmt.Sprintf("transport: authentication handshake failed: ClientHandshake Certificate SerialNumber %v revoked", peerSerialNum.String())) + return nil, nil, fmt.Errorf("transport: authentication handshake failed: ClientHandshake Certificate SerialNumber %v revoked", peerSerialNum.String()) } if len(addrSplites) > 0 { //服务端证书的序列号,已经其IP地址 @@ -162,7 +161,7 @@ func (c *Tls) ClientHandshake(ctx context.Context, authority string, rawConn net return WrapSyscallConn(rawConn, conn), tlsInfo, nil } -//ServerHandshake check cert +// ServerHandshake check cert func (c *Tls) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { conn := tls.Server(rawConn, c.config) if err := conn.Handshake(); err != nil { @@ -184,7 +183,7 @@ func (c *Tls) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, if isRevoke(peerSerialNum.String()) { rawConn.Close() - return nil, nil, errors.New(fmt.Sprintf("transport: authentication handshake failed: ServerHandshake %s revoked", peerSerialNum.String())) + return nil, nil, fmt.Errorf("transport: authentication handshake failed: ServerHandshake %s revoked", peerSerialNum.String()) } addrSplites := strings.Split(rawConn.RemoteAddr().String(), ":") if len(addrSplites) > 0 { @@ -204,7 +203,7 @@ func (c *Tls) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, return WrapSyscallConn(rawConn, conn), tlsInfo, nil } -// uses c to construct a TransportCredentials based on TLS. +// uses c to construct a TransportCredentials based on TLS. func newTLS(c *tls.Config) credentials.TransportCredentials { tc := &Tls{} tc.config = CloneTLSConfig(c) diff --git a/plugin/p2p/gossip/version.go b/plugin/p2p/gossip/version.go index df4a709162..0caf2873e7 100644 --- a/plugin/p2p/gossip/version.go +++ b/plugin/p2p/gossip/version.go @@ -13,7 +13,7 @@ package gossip //p2p版本区间 10020, 11000 -//历史版本 +// 历史版本 const ( //p2p广播交易哈希而非完整区块数据 lightBroadCastVersion = 10030 diff --git a/plugin/store/kvmvcc/kvmvccdb_test.go b/plugin/store/kvmvcc/kvmvccdb_test.go index ce58d301e3..bcd6d49da3 100644 --- a/plugin/store/kvmvcc/kvmvccdb_test.go +++ b/plugin/store/kvmvcc/kvmvccdb_test.go @@ -718,7 +718,7 @@ func BenchmarkSet(b *testing.B) { fmt.Println("mpt BenchmarkSet cost time is", end.Sub(start), "num is", b.N) } -//上一个用例,一次性插入多对kv;本用例每次插入30对kv,分多次插入,测试性能表现。 +// 上一个用例,一次性插入多对kv;本用例每次插入30对kv,分多次插入,测试性能表现。 func BenchmarkStoreSet(b *testing.B) { dir, err := ioutil.TempDir("", "example") assert.Nil(b, err) @@ -790,7 +790,7 @@ func BenchmarkSetIter(b *testing.B) { fmt.Println("kvmvcc BenchmarkSet cost time is", end.Sub(start), "num is", b.N) } -//一次设定多对kv,测试一次的时间/多少对kv,来算平均一对kv的耗时。 +// 一次设定多对kv,测试一次的时间/多少对kv,来算平均一对kv的耗时。 func BenchmarkMemSet(b *testing.B) { dir, err := ioutil.TempDir("", "example") assert.Nil(b, err) @@ -824,7 +824,7 @@ func BenchmarkMemSet(b *testing.B) { fmt.Println("kvmvcc BenchmarkMemSet cost time is", end.Sub(start), "num is", b.N) } -//一次设定30对kv,设定N次,计算每次设定30对kv的耗时。 +// 一次设定30对kv,设定N次,计算每次设定30对kv的耗时。 func BenchmarkStoreMemSet(b *testing.B) { dir, err := ioutil.TempDir("", "example") assert.Nil(b, err) @@ -947,7 +947,7 @@ func BenchmarkStoreCommit(b *testing.B) { b.StopTimer() } -//一次设定多对kv,测试一次的时间/多少对kv,来算平均一对kv的耗时。 +// 一次设定多对kv,测试一次的时间/多少对kv,来算平均一对kv的耗时。 func BenchmarkIterMemSet(b *testing.B) { dir, err := ioutil.TempDir("", "example") assert.Nil(b, err) diff --git a/plugin/store/kvmvccmavl/kvmvcc_mavl.go b/plugin/store/kvmvccmavl/kvmvcc_mavl.go index 7fd80f5867..5cbf640629 100644 --- a/plugin/store/kvmvccmavl/kvmvcc_mavl.go +++ b/plugin/store/kvmvccmavl/kvmvcc_mavl.go @@ -65,7 +65,7 @@ func init() { types.RegFork("store-kvmvccmavl", InitFork) } -//InitFork ... +// InitFork ... func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork("store-kvmvccmavl", "ForkKvmvccmavl", 0) } @@ -534,7 +534,7 @@ func setDelMavl(state int32) { atomic.StoreInt32(&delMavlDataState, state) } -//CompactDelMavl ... +// CompactDelMavl ... func CompactDelMavl(db dbm.DB) { setDelMavl(delMavlStateStart) defer setDelMavl(delMavlStateEnd) diff --git a/plugin/store/kvmvccmavl/kvmvcc_mavl_test.go b/plugin/store/kvmvccmavl/kvmvcc_mavl_test.go index 6f542df3b3..7596b333b4 100644 --- a/plugin/store/kvmvccmavl/kvmvcc_mavl_test.go +++ b/plugin/store/kvmvccmavl/kvmvcc_mavl_test.go @@ -1417,7 +1417,7 @@ func benchmarkSet(b *testing.B, isResetForkHeight bool) { fmt.Println("mpt BenchmarkSet cost time is", end.Sub(start), "num is", b.N) } -//上一个用例,一次性插入多对kv;本用例每次插入30对kv,分多次插入,测试性能表现。 +// 上一个用例,一次性插入多对kv;本用例每次插入30对kv,分多次插入,测试性能表现。 func BenchmarkStoreSetkmvccMavl(b *testing.B) { benchmarkStoreSet(b, false) } func BenchmarkStoreSetkmvcc(b *testing.B) { benchmarkStoreSet(b, true) } @@ -1509,7 +1509,7 @@ func benchmarkSetIter(b *testing.B, isResetForkHeight bool) { fmt.Println("kvmvcc BenchmarkSet cost time is", end.Sub(start), "num is", b.N) } -//一次设定多对kv,测试一次的时间/多少对kv,来算平均一对kv的耗时。 +// 一次设定多对kv,测试一次的时间/多少对kv,来算平均一对kv的耗时。 func BenchmarkMemSetkmvccMavl(b *testing.B) { benchmarkMemSet(b, false) } func BenchmarkMemSetkmvcc(b *testing.B) { benchmarkMemSet(b, true) } @@ -1553,7 +1553,7 @@ func benchmarkMemSet(b *testing.B, isResetForkHeight bool) { fmt.Println("kvmvcc BenchmarkMemSet cost time is", end.Sub(start), "num is", b.N) } -//一次设定30对kv,设定N次,计算每次设定30对kv的耗时。 +// 一次设定30对kv,设定N次,计算每次设定30对kv的耗时。 func BenchmarkStoreMemSetkmvccMavl(b *testing.B) { benchmarkStoreMemSet(b, false) } func BenchmarkStoreMemSetkmvcc(b *testing.B) { benchmarkStoreMemSet(b, true) } @@ -1708,7 +1708,7 @@ func benchmarkStoreCommit(b *testing.B, isResetForkHeight bool) { func BenchmarkIterMemSetkmvccMavl(b *testing.B) { benchmarkIterMemSet(b, false) } func BenchmarkIterMemSetkmvcc(b *testing.B) { benchmarkIterMemSet(b, true) } -//一次设定多对kv,测试一次的时间/多少对kv,来算平均一对kv的耗时。 +// 一次设定多对kv,测试一次的时间/多少对kv,来算平均一对kv的耗时。 func benchmarkIterMemSet(b *testing.B, isResetForkHeight bool) { dir, err := ioutil.TempDir("", "example") assert.Nil(b, err) diff --git a/plugin/store/kvmvccmavl/kvmvccdb.go b/plugin/store/kvmvccmavl/kvmvccdb.go index f9ed3e2459..d8d78372ea 100644 --- a/plugin/store/kvmvccmavl/kvmvccdb.go +++ b/plugin/store/kvmvccmavl/kvmvccdb.go @@ -275,7 +275,7 @@ func (mvccs *KVMVCCStore) saveKVSets(kvset []*types.KeyValue, sync bool) { dbm.MustWrite(storeBatch) } -//GetMaxVersion GetMaxVersion 获取当前最大高度 +// GetMaxVersion GetMaxVersion 获取当前最大高度 func (mvccs *KVMVCCStore) GetMaxVersion() (int64, error) { return mvccs.mvcc.GetMaxVersion() } @@ -327,7 +327,7 @@ func calcHash(datas proto.Message) []byte { return common.Sha256(b) } -//SetRdm ... +// SetRdm ... func (mvccs *KVMVCCStore) SetRdm(datas *types.StoreSet, mavlHash []byte, sync bool) ([]byte, error) { mvccHash := calcHash(datas) // 取出前一个hash映射 @@ -356,7 +356,7 @@ func (mvccs *KVMVCCStore) SetRdm(datas *types.StoreSet, mavlHash []byte, sync bo return hash, nil } -//MemSetRdm ... +// MemSetRdm ... func (mvccs *KVMVCCStore) MemSetRdm(datas *types.StoreSet, mavlHash []byte, sync bool) ([]byte, error) { beg := types.Now() defer func() { @@ -408,13 +408,13 @@ func (mvccs *KVMVCCStore) MemSetRdm(datas *types.StoreSet, mavlHash []byte, sync return hash, nil } -//GetHashRdm ... +// GetHashRdm ... func (mvccs *KVMVCCStore) GetHashRdm(hash []byte, height int64) ([]byte, error) { key := calcRdmKey(hash, height) return mvccs.db.Get(key) } -//GetFirstHashRdm ... +// GetFirstHashRdm ... func (mvccs *KVMVCCStore) GetFirstHashRdm(hash []byte) ([]byte, error) { prefix := append(rdmHashPrefix, hash...) list := dbm.NewListHelper(mvccs.db) @@ -468,7 +468,7 @@ func pruningMVCCData(db dbm.DB, safeHeight int64) { if height >= safeHeight { continue } - if bytes.Compare(key, newKey) != 0 { + if !bytes.Equal(key, newKey) { newKey = make([]byte, len(key)) copy(newKey, key) continue diff --git a/plugin/store/mpt/db/database.go b/plugin/store/mpt/db/database.go index 30ac08e71f..da202684e8 100644 --- a/plugin/store/mpt/db/database.go +++ b/plugin/store/mpt/db/database.go @@ -207,7 +207,7 @@ func (db *Database) InsertBlob(hash common.Hash, blob []byte) { db.insert(hash, blob, rawNode(blob)) } -//把flags 去掉,减少内存占用 +// 把flags 去掉,减少内存占用 func simplifyNode(n node) node { switch n := n.(type) { case *shortNode: diff --git a/plugin/store/mpt/db2/rlp/decode.go b/plugin/store/mpt/db2/rlp/decode.go index 71ca063cea..844e163732 100644 --- a/plugin/store/mpt/db2/rlp/decode.go +++ b/plugin/store/mpt/db2/rlp/decode.go @@ -101,9 +101,9 @@ type Decoder interface { // rules for the field such that input values of size zero decode as a nil // pointer. This tag can be useful when decoding recursive types. // -// type StructWithEmptyOK struct { -// Foo *[20]byte `rlp:"nil"` -// } +// type StructWithEmptyOK struct { +// Foo *[20]byte `rlp:"nil"` +// } // // To decode into a slice, the input must be a list and the resulting // slice will contain the input elements in order. For byte slices, @@ -123,8 +123,8 @@ type Decoder interface { // To decode into an interface value, Decode stores one of these // in the value: // -// []interface{}, for RLP lists -// []byte, for RLP strings +// []interface{}, for RLP lists +// []byte, for RLP strings // // Non-empty interface types are not supported, nor are booleans, // signed integers, floating point numbers, maps, channels and @@ -134,7 +134,7 @@ type Decoder interface { // and may be vulnerable to panics cause by huge value sizes. If // you need an input limit, use // -// NewStream(r, limit).Decode(val) +// NewStream(r, limit).Decode(val) func Decode(r io.Reader, val interface{}) error { // TODO: this could use a Stream from a pool. return NewStream(r, 0).Decode(val) diff --git a/plugin/store/mpt/mpt_test.go b/plugin/store/mpt/mpt_test.go index 99c7e2826e..bce9d8f303 100644 --- a/plugin/store/mpt/mpt_test.go +++ b/plugin/store/mpt/mpt_test.go @@ -172,7 +172,7 @@ func GetRandomString(length int) string { return common.GetRandPrintString(20, length) } -//目前正常情况下get 都是一个一个获取的 +// 目前正常情况下get 都是一个一个获取的 func BenchmarkGet(b *testing.B) { dir, err := ioutil.TempDir("", "example") assert.Nil(b, err) diff --git a/version/version.go b/version/version.go index d95ce52b5e..ff69e73b6d 100644 --- a/version/version.go +++ b/version/version.go @@ -5,7 +5,7 @@ import ( "runtime" ) -//var version control +// var version control var ( Version = "1.71.1" GitCommit string @@ -16,7 +16,7 @@ var ( Platform = fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH) ) -//GetVersion 获取版本信息 +// GetVersion 获取版本信息 func GetVersion() string { if GitCommit != "" { return Version + "-" + GitCommit From abbacc6f1d265141ce17a20675bda92d0182f9f3 Mon Sep 17 00:00:00 2001 From: king Date: Tue, 1 Sep 2026 10:13:33 +0000 Subject: [PATCH 04/11] fix: resolve shellcheck warnings and UNKOWN typo in RPC placeholders - issuance/relay/paracross test-rpc.sh: capture \$? into a variable instead of reading it after echo/condition (SC2319/SC2320); relay reported echo's exit code (always 0) instead of the intended failure - auto_deploy.sh: capture SendFileAndDecompressFile exit code before the if/elif, the elif branch previously could never be taken - mix testcase.sh: quote \$(cat ...) to prevent word splitting (SC2046) - dockerRelayerTestEvm.sh: drop leftover 'fix}_ebrelayer\${name}' junk line - qbft/tendermint: UNKOWN -> UNKNOWN in Query_NodeInfo placeholder strings Co-Authored-By: Claude --- .../consensus/tendermint/tools/auto_deploy.sh | 7 +- .../cmd/build/dockerRelayerTestEvm.sh | 1 - plugin/dapp/issuance/cmd/test/test-rpc.sh | 110 +++++++++++------- plugin/dapp/mix/cmd/build/testcase.sh | 10 +- plugin/dapp/paracross/cmd/test/test-rpc.sh | 9 +- plugin/dapp/relay/cmd/test/test-rpc.sh | 6 +- 6 files changed, 84 insertions(+), 59 deletions(-) diff --git a/plugin/consensus/tendermint/tools/auto_deploy.sh b/plugin/consensus/tendermint/tools/auto_deploy.sh index c3a7f8f275..a8cef4ceee 100755 --- a/plugin/consensus/tendermint/tools/auto_deploy.sh +++ b/plugin/consensus/tendermint/tools/auto_deploy.sh @@ -81,7 +81,7 @@ GetUserNamePasswdAndPath() { echo "Does the config of destination right?(yes/no)" read input - if [ "X${input}" = "Xno" ]; then + if [ "${input}" = "no" ]; then echo "The config file is wrong. You can config it manually." return 1 fi @@ -218,10 +218,11 @@ main() { # Send and decompress the package SendFileAndDecompressFile - if [ $? -eq 1 ]; then + ret=$? + if [ $ret -eq 1 ]; then echo "Send file err and exit soon..." exit - elif [ $? -eq 2 ]; then + elif [ $ret -eq 2 ]; then echo "Decompress file err and exit soon..." fi } diff --git a/plugin/dapp/bridgevmxgo/cmd/build/dockerRelayerTestEvm.sh b/plugin/dapp/bridgevmxgo/cmd/build/dockerRelayerTestEvm.sh index 718a5bcbab..a931d3606b 100755 --- a/plugin/dapp/bridgevmxgo/cmd/build/dockerRelayerTestEvm.sh +++ b/plugin/dapp/bridgevmxgo/cmd/build/dockerRelayerTestEvm.sh @@ -292,7 +292,6 @@ function get_evm_cli() { CLIAeth="docker exec ${dockerNamePrefix}-ebrelayera-1 /root/ebcli_A --node_addr http://${docker_ganachetesteth_ip}:8545 --eth_chain_name Ethereum" CLIAbsc="docker exec ${dockerNamePrefix}-ebrelayera-1 /root/ebcli_A --node_addr http://${docker_ganachetestbsc_ip}:8545 --eth_chain_name Binance" -fix}_ebrelayer${name} EvmxgoBoss4xCLI="./evmxgoboss4x --rpc_laddr http://${docker_chain33_ip}:8901 --paraName user.p.para. --chainID ${chain33ID}" } } diff --git a/plugin/dapp/issuance/cmd/test/test-rpc.sh b/plugin/dapp/issuance/cmd/test/test-rpc.sh index 9034be589c..98824b787a 100755 --- a/plugin/dapp/issuance/cmd/test/test-rpc.sh +++ b/plugin/dapp/issuance/cmd/test/test-rpc.sh @@ -33,8 +33,9 @@ issuance_Create() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" "${IssuancePriv1}" ${MAIN_HTTP} ISSU_ID=$RAW_TX_HASH @@ -71,8 +72,9 @@ issuance_Feed() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" "${IssuancePriv2}" ${MAIN_HTTP} chain33_BlockWait 1 "${MAIN_HTTP}" @@ -90,8 +92,9 @@ issuance_Debt() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" "${IssuancePriv3}" ${MAIN_HTTP} DEBT_ID=$RAW_TX_HASH @@ -114,8 +117,9 @@ issuance_Repay() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" "${IssuancePriv3}" ${MAIN_HTTP} chain33_BlockWait 1 "${MAIN_HTTP}" @@ -132,8 +136,9 @@ issuance_Close() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" "${IssuancePriv1}" ${MAIN_HTTP} chain33_BlockWait 1 "${MAIN_HTTP}" @@ -150,8 +155,9 @@ collateralize_Manage() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" "${IssuancePriv1}" ${MAIN_HTTP} ISSU_ID=$RAW_TX_HASH @@ -170,8 +176,9 @@ collateralize_Create() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" "${IssuancePriv3}" ${MAIN_HTTP} COLL_ID=$RAW_TX_HASH @@ -194,8 +201,9 @@ collateralize_Feed() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" "${IssuancePriv2}" ${MAIN_HTTP} chain33_BlockWait 1 "${MAIN_HTTP}" @@ -213,8 +221,9 @@ collateralize_Borrow() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" "${CollateralizePriv}" ${MAIN_HTTP} BORROW_ID=$RAW_TX_HASH @@ -252,8 +261,9 @@ collateralize_Repay() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" "${CollateralizePriv}" ${MAIN_HTTP} chain33_BlockWait 1 ${MAIN_HTTP} @@ -270,8 +280,9 @@ collateralize_Retrieve() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" "${IssuancePriv3}" ${MAIN_HTTP} chain33_BlockWait 1 ${MAIN_HTTP} @@ -368,8 +379,9 @@ manage() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" ${SystemManager} ${MAIN_HTTP} echo "========== # issuance add issuance-manage end ==========" @@ -381,8 +393,9 @@ manage() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "$tx" ${SystemManager} ${MAIN_HTTP} echo "========== # issuance add issuance-fund end ==========" @@ -422,8 +435,9 @@ token() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "${tx}" "${TokenSuperManager}" "${MAIN_HTTP}" echo "========== # issuance add token token-blacklist end ==========" @@ -434,8 +448,9 @@ token() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "${tx}" "${TokenSuperManager}" "${MAIN_HTTP}" echo "========== # issuance add token token-finisher end ==========" @@ -446,8 +461,9 @@ token() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "${tx}" "${TokenSuperManager}" "${MAIN_HTTP}" echo "========== # issuance add token precreate end ==========" @@ -458,8 +474,9 @@ token() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "${tx}" "${TokenSuperManager}" "${MAIN_HTTP}" echo "========== # issuance add token finish end ==========" @@ -470,8 +487,9 @@ token() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "${tx}" "${TokenSuperManager}" "${MAIN_HTTP}" @@ -479,8 +497,9 @@ token() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "${tx}" "${TokenSuperManager}" "${MAIN_HTTP}" @@ -488,8 +507,9 @@ token() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "${tx}" "${TokenSuperManager}" "${MAIN_HTTP}" echo "========== # issuance add token transfer end ==========" @@ -500,8 +520,9 @@ token() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "${tx}" "${IssuancePriv1}" "${MAIN_HTTP}" @@ -509,8 +530,9 @@ token() { data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") ok=$(jq '(.execer != "")' <<<"$data") - [ "$ok" == true ] - echo_rst "$FUNCNAME" "$?" + rst=1 + [ "$ok" == true ] && rst=0 + echo_rst "$FUNCNAME" "$rst" chain33_SignAndSendTx "${tx}" "${IssuancePriv3}" "${MAIN_HTTP}" diff --git a/plugin/dapp/mix/cmd/build/testcase.sh b/plugin/dapp/mix/cmd/build/testcase.sh index 417015c347..4d789a59bc 100644 --- a/plugin/dapp/mix/cmd/build/testcase.sh +++ b/plugin/dapp/mix/cmd/build/testcase.sh @@ -95,12 +95,12 @@ function mix_transfer() { ${CLI} send mix config register -r 18437326986701045682163784849869247633492934399146571227371858493337922483431 -e a97592e700eb0f87c5738b35c8d460ce33a4a59bde6128081ddd042c3c262f76 -a 1MCftFynyvG2F4ED5mdHYgziDxx6vDrScs -k 0xcacb1f5d51700aea07fca2246ab43b0917d70405c65edea9b5063d72eb5c6b71 ##config deposit circuit vk - ${CLI} send mix config vk -c 0 -z $(cat ./gnark/circuit_deposit.vk) -k 4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01 + ${CLI} send mix config vk -c 0 -z "$(cat ./gnark/circuit_deposit.vk)" -k 4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01 ##config withdraw vk - ${CLI} send mix config vk -c 1 -z $(cat ./gnark/circuit_withdraw.vk) -k 4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01 #transferInput - ${CLI} send mix config vk -c 2 -z $(cat ./gnark/circuit_transfer_input.vk) -k 4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01 #transferOutput - ${CLI} send mix config vk -c 3 -z $(cat ./gnark/circuit_transfer_output.vk) -k 4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01 #auth - ${CLI} send mix config vk -c 4 -z $(cat ./gnark/circuit_auth.vk) -k 4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01 + ${CLI} send mix config vk -c 1 -z "$(cat ./gnark/circuit_withdraw.vk)" -k 4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01 #transferInput + ${CLI} send mix config vk -c 2 -z "$(cat ./gnark/circuit_transfer_input.vk)" -k 4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01 #transferOutput + ${CLI} send mix config vk -c 3 -z "$(cat ./gnark/circuit_transfer_output.vk)" -k 4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01 #auth + ${CLI} send mix config vk -c 4 -z "$(cat ./gnark/circuit_auth.vk)" -k 4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01 } function mix_deposit() { diff --git a/plugin/dapp/paracross/cmd/test/test-rpc.sh b/plugin/dapp/paracross/cmd/test/test-rpc.sh index 7fcfbb842f..e4fc32606c 100755 --- a/plugin/dapp/paracross/cmd/test/test-rpc.sh +++ b/plugin/dapp/paracross/cmd/test/test-rpc.sh @@ -29,8 +29,9 @@ function paracross_QueryParaBalance() { req='{"method":"Chain33.GetBalance", "params":[{"addresses" : ["'"$1"'"], "execer" : "'"${exec}"'","asset_exec":"paracross","asset_symbol":"'"${symbol}"'"}]}' resp=$(curl -ksd "$req" "${para_http}") balance=$(jq -r '.result[0].balance' <<<"$resp") + rst=$? echo "$balance" - return $? + return $rst } function paracross_QueryMainBalance() { @@ -46,8 +47,9 @@ function paracross_QueryMainBalance() { req='{"method":"Chain33.GetBalance", "params":[{"addresses" : ["'"$1"'"], "execer" : "paracross"}]}' resp=$(curl -ksd "$req" "${main_http}") balance=$(jq -r '.result[0].balance' <<<"$resp") + rst=$? echo "$balance" - return $? + return $rst } function paracross_QueryMainAssetBalance() { @@ -68,8 +70,9 @@ function paracross_QueryMainAssetBalance() { req='{"method":"Chain33.GetBalance", "params":[{"addresses" : ["'"$1"'"], "execer" : "'"${exec}"'","asset_exec":"paracross","asset_symbol":"'"${symbol}"'"}]}' resp=$(curl -ksd "$req" "${main_http}") balance=$(jq -r '.result[0].balance' <<<"$resp") + rst=$? echo "$balance" - return $? + return $rst } function paracross_Transfer_Withdraw_Inner() { diff --git a/plugin/dapp/relay/cmd/test/test-rpc.sh b/plugin/dapp/relay/cmd/test/test-rpc.sh index 3b4cae57c8..775101acd2 100755 --- a/plugin/dapp/relay/cmd/test/test-rpc.sh +++ b/plugin/dapp/relay/cmd/test/test-rpc.sh @@ -33,7 +33,7 @@ relay_CreateRawRelayAcceptTx() { id=$(curl -ksd "{$req}" ${MAIN_HTTP} | jq -r ".result.relayorders[0].id") if [ "$id" == null ]; then echo "id is null" - echo_rst "$FUNCNAME" "$?" + echo_rst "$FUNCNAME" "1" exit 1 fi @@ -48,7 +48,7 @@ relay_CreateRawRelayRevokeTx() { id=$(curl -ksd "{$req}" ${MAIN_HTTP} | jq -r ".result.relayorders[0].id") if [ "$id" == null ]; then echo "id is null" - echo_rst "$FUNCNAME" "$?" + echo_rst "$FUNCNAME" "1" exit 1 fi @@ -63,7 +63,7 @@ relay_CreateRawRelayConfirmTx() { id=$(curl -ksd "{$req}" ${MAIN_HTTP} | jq -r ".result.relayorders[0].id") if [ "$id" == null ]; then echo "id is null" - echo_rst "$FUNCNAME" "$?" + echo_rst "$FUNCNAME" "1" exit 1 fi From c5c8a3a452fc3a7efbe6f2921fcfc72eabfd5392 Mon Sep 17 00:00:00 2001 From: king Date: Tue, 1 Sep 2026 10:13:33 +0000 Subject: [PATCH 05/11] ci: enable checkgofmt and linter in ci_base workflow Un-comment make checkgofmt and make linter (disabled in 7c6910a03 and ca1288b4e in 2025-06). Both now pass: golinter.sh is fixed, shellcheck is gated at -S warning, and the repo is gofmt/goimports clean. Co-Authored-By: Claude --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 48d1180a62..3ea97fea38 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -28,8 +28,8 @@ jobs: - name: Lint run: | make largefile-check - # make checkgofmt && make fmt_go - # make linter + make checkgofmt + make linter make unit-test: From fd5d38ff18035d26e96f2d0580988abeea5c1519 Mon Sep 17 00:00:00 2001 From: king Date: Wed, 2 Sep 2026 04:12:42 +0000 Subject: [PATCH 06/11] ci: replace jenkins/gitlab autotest modes with ticket module integration test The jerkinsci autotest mode (make autotest_ci) ran the same autotest binary and case set as build.yml's existing autotest job (local mode), only wrapped in docker, so its CI job was redundant. The gitlabci mode (make autotest_tick) is an unmaintained upstream script whose 'close auto mining then expect blocks' logic does not match current chain behavior (height stays 0, no ticket bind step). Replace both with a ticket dapp integration test: - plugin/dapp/ticket/cmd/build/testcase.sh: standard dapp testcase covering the ticket lifecycle on the main chain (which already runs ticket consensus): auto-mining toggle, CreateBindMiner + sign/send, TicketList bound/closed, GetTicketCount, CloseTickets - build.sh now copies cmd/build into build/ci/ticket like other dapps - build_ticket.yml runs make docker-compose dapp=ticket Note: an intermediate attempt enabled COMPOSE_COMPATIBILITY so the jerkinsci container name matched the upstream script's v1-style name; that path was abandoned along with ci_autotest.yml. Co-Authored-By: Claude --- .github/workflows/build_ticket.yml | 33 ++++++++++++ .github/workflows/ci_autotest.yml | 65 ------------------------ plugin/dapp/ticket/cmd/build.sh | 9 +++- plugin/dapp/ticket/cmd/build/testcase.sh | 54 ++++++++++++++++++++ 4 files changed, 94 insertions(+), 67 deletions(-) create mode 100644 .github/workflows/build_ticket.yml delete mode 100644 .github/workflows/ci_autotest.yml create mode 100644 plugin/dapp/ticket/cmd/build/testcase.sh diff --git a/.github/workflows/build_ticket.yml b/.github/workflows/build_ticket.yml new file mode 100644 index 0000000000..5391883cf5 --- /dev/null +++ b/.github/workflows/build_ticket.yml @@ -0,0 +1,33 @@ +name: ci_ticket +on: [push, pull_request] + +# ticket 模块集成测试(plugin/dapp/ticket/cmd/build/testcase.sh)。 +# 主链 [consensus] 本身就是 ticket 共识(chain33.toml name="ticket"), +# 测试覆盖 ticket 生命周期:自动挖矿开关、买票绑定、票查询、解绑。 +# 替代原 Jenkins/GitLab 时代的 autotest_tick(chain33 build/autotest/gitlabci +# 双节点脚本,其"关闭自动挖矿后等出块"的逻辑与当前链行为不匹配且无维护)。 + +jobs: + ci_ticket: + name: ci_ticket + runs-on: ubuntu-22.04 + timeout-minutes: 60 + steps: + - name: checkout + uses: actions/checkout@v3 + + - name: Set up Golang + uses: actions/setup-go@v3 + with: + go-version-file: 'go.mod' + id: go + + - name: set go env + run: export PATH=${PATH}:`go env GOPATH`/bin + + - name: deploy + run: make docker-compose dapp=ticket + + - name: cleanup + if: always() + run: make docker-compose-down dapp=ticket diff --git a/.github/workflows/ci_autotest.yml b/.github/workflows/ci_autotest.yml deleted file mode 100644 index 27735d55f9..0000000000 --- a/.github/workflows/ci_autotest.yml +++ /dev/null @@ -1,65 +0,0 @@ -name: ci_autotest -on: [push, pull_request] - -# 对应 Makefile 的 autotest_ci / autotest_tick: -# autotest_ci -> chain33 build/autotest/jerkinsci 目录,solo 模式跑全量测试用例 -# autotest_tick -> chain33 build/autotest/gitlabci 目录,双节点 + ticket 挖矿场景 -# 两者都是 docker-compose 起链后跑 autotest 二进制,与 build.yml 的 -# `make autotest dapp=all`(local 模式,docker-compose 起 dapp 集群)互补。 - -jobs: - autotest_ci: - name: autotest_ci - runs-on: ubuntu-22.04 - timeout-minutes: 90 - steps: - - name: checkout - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - - name: Set up Golang - uses: actions/setup-go@v3 - with: - go-version-file: 'go.mod' - id: go - - - name: set go env - run: export PATH=${PATH}:`go env GOPATH`/bin - - - name: autotest ci - run: | - make build_ci - make autotest_ci - - - name: cleanup - if: always() - run: make clean || true - - autotest_tick: - name: autotest_tick - runs-on: ubuntu-22.04 - timeout-minutes: 90 - steps: - - name: checkout - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - - name: Set up Golang - uses: actions/setup-go@v3 - with: - go-version-file: 'go.mod' - id: go - - - name: set go env - run: export PATH=${PATH}:`go env GOPATH`/bin - - - name: autotest tick - run: | - make build_ci - make autotest_tick - - - name: cleanup - if: always() - run: make clean || true diff --git a/plugin/dapp/ticket/cmd/build.sh b/plugin/dapp/ticket/cmd/build.sh index 8601313f74..6f8ea8649d 100755 --- a/plugin/dapp/ticket/cmd/build.sh +++ b/plugin/dapp/ticket/cmd/build.sh @@ -1,9 +1,14 @@ -#!/bin/sh +#!/usr/bin/env bash strpwd=$(pwd) strcmd=${strpwd##*dapp/} strapp=${strcmd%/cmd*} +OUT_DIR="${1}/$strapp" +mkdir -p "${OUT_DIR}" +# shellcheck disable=SC2086 +cp ./build/* "${OUT_DIR}" + OUT_TESTDIR="${1}/dapptest/$strapp" mkdir -p "${OUT_TESTDIR}" -cp ./test/test-rpc.sh "${OUT_TESTDIR}" +cp ./test/* "${OUT_TESTDIR}" diff --git a/plugin/dapp/ticket/cmd/build/testcase.sh b/plugin/dapp/ticket/cmd/build/testcase.sh new file mode 100644 index 0000000000..5522bcae00 --- /dev/null +++ b/plugin/dapp/ticket/cmd/build/testcase.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# shellcheck disable=SC2128 +# shellcheck source=/dev/null + +# ticket 模块集成测试:主链 [consensus] 本身就是 ticket 共识(chain33.toml +# name="ticket",genesis 票归 returnAddr),基础链 init_nodes 已导入 +# returnAddr 私钥并解锁钱包,这里直接对 NODE3 验证 ticket 生命周期。 + +RETURN_ADDR="14KEKbYtKKQm4wMthSK9J4La4nAiidGozt" # [consensus] genesis 地址 +RETURN_KEY="CC38546E9E659D15E6B4893F0AB32A06D103931A8230B0BDE71459D2B27D6944" +MINER_ADDR="12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv" # init_nodes 导入的挖矿地址 +TICKET_PRICE=$((10000 * 100000000)) # 10000 coins + +function ticket() { + if [ "${2}" == "test" ]; then + echo "========================== ticket test ==========================" + MAIN_HTTP="http://${3}:8801" + set +e + + # 1. 初始出块正常(minerstart=true 自动挖矿) + chain33_BlockWait 1 "${MAIN_HTTP}" + + # 2. 节点自动挖矿开关(关->开,验证 ticket 挖矿开关 API) + req='{"method":"ticket.SetAutoMining","params":[{"flag":false}]}' + chain33_Http "$req" "${MAIN_HTTP}" '(.error|not) and (.result.isOK == true)' "ticket_SetAutoMiningOff" + req='{"method":"ticket.SetAutoMining","params":[{"flag":true}]}' + chain33_Http "$req" "${MAIN_HTTP}" '(.error|not) and (.result.isOK == true)' "ticket_SetAutoMiningOn" + + # 3. 买票并绑定矿工(origin 出钱,票归 bind 矿工) + req='{"method":"ticket.CreateBindMiner","params":[{"bindAddr":"'"${MINER_ADDR}"'","originAddr":"'"${RETURN_ADDR}"'","amount":'"${TICKET_PRICE}"',"checkBalance":true}]}' + chain33_Http "$req" "${MAIN_HTTP}" '(.error|not)' "ticket_CreateBindMiner" ".result.txHex" + chain33_SignAndSendTx "${RETURN_RESP}" "${RETURN_KEY}" "${MAIN_HTTP}" + chain33_BlockWait 1 "${MAIN_HTTP}" + + # 4. 查询绑定状态的票 + req='{"method":"Chain33.Query","params":[{"execer":"ticket","funcName":"TicketList","payload":{"addr":"'"${MINER_ADDR}"'","status":1}}]}' + chain33_Http "$req" "${MAIN_HTTP}" '(.error|not) and (.result.tickets|length > 0)' "ticket_TicketList" + + # 5. 票总数 > 0 + req='{"method":"ticket.GetTicketCount","params":[{}]}' + chain33_Http "$req" "${MAIN_HTTP}" '(.error|not) and (.result > 0)' "ticket_GetTicketCount" + + # 6. 解绑(关闭票) + req='{"method":"ticket.CloseTickets","params":[{"minerAddress":"'"${MINER_ADDR}"'"}]}' + chain33_Http "$req" "${MAIN_HTTP}" '(.error|not)' "ticket_CloseTickets" + chain33_BlockWait 1 "${MAIN_HTTP}" + + # 7. 查询已关闭状态的票 + req='{"method":"Chain33.Query","params":[{"execer":"ticket","funcName":"TicketList","payload":{"addr":"'"${MINER_ADDR}"'","status":2}}]}' + chain33_Http "$req" "${MAIN_HTTP}" '(.error|not) and (.result.tickets|length > 0)' "ticket_TicketListClosed" + + echo "========================== ticket test end ==========================" + fi +} From 9765945a7a4a19caf7a130ab276c4137fc6bd863 Mon Sep 17 00:00:00 2001 From: king Date: Wed, 2 Sep 2026 05:17:35 +0000 Subject: [PATCH 07/11] ci: add native windows build workflow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit manual_make_bin.yml 的 make all-arch 是在 ubuntu 上用 GOOS=windows 交叉编译(CGO_ENABLED=0),只验证能产出 PE 文件,不经过 Windows 原生工具链,也不执行 build.bat。删除 appveyor.yml 后这部分信号缺失。 新增 build_windows.yml,在 windows-2022 runner 上跑 build.bat, 对应原 appveyor 的 test_script。go 版本从 go.mod 读取,不再像 appveyor 那样硬编码 C:\go122;模块化项目无需 GOPATH/clone_folder。 build.bat 用 shell: cmd 调用,PowerShell 下 bat 的非零退出码不能 可靠传播。 Co-Authored-By: Claude Fable 5 --- .github/workflows/build_windows.yml | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 .github/workflows/build_windows.yml diff --git a/.github/workflows/build_windows.yml b/.github/workflows/build_windows.yml new file mode 100644 index 0000000000..c02ef5f1c2 --- /dev/null +++ b/.github/workflows/build_windows.yml @@ -0,0 +1,31 @@ +name: build_windows +on: [push, pull_request] + +jobs: + build-windows: + name: build on windows + runs-on: windows-2022 + steps: + - uses: actions/checkout@v4 + - name: Set up Golang + uses: actions/setup-go@v5 + with: + go-version-file: 'go.mod' + id: go + + - name: go env + run: | + go version + go env + + - name: build + shell: cmd + run: build.bat + + - name: Upload artifact bin + uses: actions/upload-artifact@v4 + with: + name: chain33-windows-amd64 + path: | + chain33.exe + chain33-cli.exe From 480a49c46875849f64c46fbf0772e0c8e43ec92e Mon Sep 17 00:00:00 2001 From: king Date: Wed, 2 Sep 2026 08:58:48 +0000 Subject: [PATCH 08/11] ci: drop ticket module integration test, keep dapptest coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review feedback: the ticket job added in fd5d38ff1 was green but ran nothing — testcase.sh's helpers (chain33_Http, chain33_SignAndSendTx, RETURN_RESP) are only loaded by docker-compose.sh when DAPP is empty or paracross, so under dapp=ticket every call was "command not found" and set +e let the script exit 0. The same ticket lifecycle assertions already run in build.yml's ci_base job: make docker-compose (no dapp) sources dapp-test-rpc.sh, whose dapp_test_rpc() runs dapptest/ticket/test-rpc.sh separately and fails the job on non-zero exit — the same mechanism that covers relay. So the dedicated job is redundant; remove build_ticket.yml, the now-dead testcase.sh, and restore ticket's build.sh to its pre-fd5d38ff1 state. autotest_tick's removal rationale (unmaintained upstream script, height stays 0) is unaffected. Co-Authored-By: Claude --- .github/workflows/build_ticket.yml | 33 --------------- plugin/dapp/ticket/cmd/build.sh | 9 +--- plugin/dapp/ticket/cmd/build/testcase.sh | 54 ------------------------ 3 files changed, 2 insertions(+), 94 deletions(-) delete mode 100644 .github/workflows/build_ticket.yml delete mode 100644 plugin/dapp/ticket/cmd/build/testcase.sh diff --git a/.github/workflows/build_ticket.yml b/.github/workflows/build_ticket.yml deleted file mode 100644 index 5391883cf5..0000000000 --- a/.github/workflows/build_ticket.yml +++ /dev/null @@ -1,33 +0,0 @@ -name: ci_ticket -on: [push, pull_request] - -# ticket 模块集成测试(plugin/dapp/ticket/cmd/build/testcase.sh)。 -# 主链 [consensus] 本身就是 ticket 共识(chain33.toml name="ticket"), -# 测试覆盖 ticket 生命周期:自动挖矿开关、买票绑定、票查询、解绑。 -# 替代原 Jenkins/GitLab 时代的 autotest_tick(chain33 build/autotest/gitlabci -# 双节点脚本,其"关闭自动挖矿后等出块"的逻辑与当前链行为不匹配且无维护)。 - -jobs: - ci_ticket: - name: ci_ticket - runs-on: ubuntu-22.04 - timeout-minutes: 60 - steps: - - name: checkout - uses: actions/checkout@v3 - - - name: Set up Golang - uses: actions/setup-go@v3 - with: - go-version-file: 'go.mod' - id: go - - - name: set go env - run: export PATH=${PATH}:`go env GOPATH`/bin - - - name: deploy - run: make docker-compose dapp=ticket - - - name: cleanup - if: always() - run: make docker-compose-down dapp=ticket diff --git a/plugin/dapp/ticket/cmd/build.sh b/plugin/dapp/ticket/cmd/build.sh index 6f8ea8649d..8601313f74 100755 --- a/plugin/dapp/ticket/cmd/build.sh +++ b/plugin/dapp/ticket/cmd/build.sh @@ -1,14 +1,9 @@ -#!/usr/bin/env bash +#!/bin/sh strpwd=$(pwd) strcmd=${strpwd##*dapp/} strapp=${strcmd%/cmd*} -OUT_DIR="${1}/$strapp" -mkdir -p "${OUT_DIR}" -# shellcheck disable=SC2086 -cp ./build/* "${OUT_DIR}" - OUT_TESTDIR="${1}/dapptest/$strapp" mkdir -p "${OUT_TESTDIR}" -cp ./test/* "${OUT_TESTDIR}" +cp ./test/test-rpc.sh "${OUT_TESTDIR}" diff --git a/plugin/dapp/ticket/cmd/build/testcase.sh b/plugin/dapp/ticket/cmd/build/testcase.sh deleted file mode 100644 index 5522bcae00..0000000000 --- a/plugin/dapp/ticket/cmd/build/testcase.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env bash -# shellcheck disable=SC2128 -# shellcheck source=/dev/null - -# ticket 模块集成测试:主链 [consensus] 本身就是 ticket 共识(chain33.toml -# name="ticket",genesis 票归 returnAddr),基础链 init_nodes 已导入 -# returnAddr 私钥并解锁钱包,这里直接对 NODE3 验证 ticket 生命周期。 - -RETURN_ADDR="14KEKbYtKKQm4wMthSK9J4La4nAiidGozt" # [consensus] genesis 地址 -RETURN_KEY="CC38546E9E659D15E6B4893F0AB32A06D103931A8230B0BDE71459D2B27D6944" -MINER_ADDR="12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv" # init_nodes 导入的挖矿地址 -TICKET_PRICE=$((10000 * 100000000)) # 10000 coins - -function ticket() { - if [ "${2}" == "test" ]; then - echo "========================== ticket test ==========================" - MAIN_HTTP="http://${3}:8801" - set +e - - # 1. 初始出块正常(minerstart=true 自动挖矿) - chain33_BlockWait 1 "${MAIN_HTTP}" - - # 2. 节点自动挖矿开关(关->开,验证 ticket 挖矿开关 API) - req='{"method":"ticket.SetAutoMining","params":[{"flag":false}]}' - chain33_Http "$req" "${MAIN_HTTP}" '(.error|not) and (.result.isOK == true)' "ticket_SetAutoMiningOff" - req='{"method":"ticket.SetAutoMining","params":[{"flag":true}]}' - chain33_Http "$req" "${MAIN_HTTP}" '(.error|not) and (.result.isOK == true)' "ticket_SetAutoMiningOn" - - # 3. 买票并绑定矿工(origin 出钱,票归 bind 矿工) - req='{"method":"ticket.CreateBindMiner","params":[{"bindAddr":"'"${MINER_ADDR}"'","originAddr":"'"${RETURN_ADDR}"'","amount":'"${TICKET_PRICE}"',"checkBalance":true}]}' - chain33_Http "$req" "${MAIN_HTTP}" '(.error|not)' "ticket_CreateBindMiner" ".result.txHex" - chain33_SignAndSendTx "${RETURN_RESP}" "${RETURN_KEY}" "${MAIN_HTTP}" - chain33_BlockWait 1 "${MAIN_HTTP}" - - # 4. 查询绑定状态的票 - req='{"method":"Chain33.Query","params":[{"execer":"ticket","funcName":"TicketList","payload":{"addr":"'"${MINER_ADDR}"'","status":1}}]}' - chain33_Http "$req" "${MAIN_HTTP}" '(.error|not) and (.result.tickets|length > 0)' "ticket_TicketList" - - # 5. 票总数 > 0 - req='{"method":"ticket.GetTicketCount","params":[{}]}' - chain33_Http "$req" "${MAIN_HTTP}" '(.error|not) and (.result > 0)' "ticket_GetTicketCount" - - # 6. 解绑(关闭票) - req='{"method":"ticket.CloseTickets","params":[{"minerAddress":"'"${MINER_ADDR}"'"}]}' - chain33_Http "$req" "${MAIN_HTTP}" '(.error|not)' "ticket_CloseTickets" - chain33_BlockWait 1 "${MAIN_HTTP}" - - # 7. 查询已关闭状态的票 - req='{"method":"Chain33.Query","params":[{"execer":"ticket","funcName":"TicketList","payload":{"addr":"'"${MINER_ADDR}"'","status":2}}]}' - chain33_Http "$req" "${MAIN_HTTP}" '(.error|not) and (.result.tickets|length > 0)' "ticket_TicketListClosed" - - echo "========================== ticket test end ==========================" - fi -} From 0f4b7e3477bc5de66c7f746ca09672a8c0381421 Mon Sep 17 00:00:00 2001 From: king Date: Wed, 2 Sep 2026 09:01:22 +0000 Subject: [PATCH 09/11] ci: unify actions/checkout@v4 and actions/setup-go@v5 across workflows Review suggestion: the new workflows mixed Node 16 actions (v3) with build_windows.yml's v4/v5; the rest of the repo (including release.yml at checkout/setup-go v2) was on the same deprecated versions. Upgrade every workflow to checkout@v4 / setup-go@v5 so no workflow depends on the deprecated Node 16 runtime. Mechanical change only; every setup-go block already pins go-version-file so v5's required version input is satisfied. YAML revalidated. Co-Authored-By: Claude --- .github/workflows/automake.yml | 4 ++-- .github/workflows/build.yml | 24 +++++++++++------------ .github/workflows/build_cross2eth.yml | 4 ++-- .github/workflows/build_evm.yml | 4 ++-- .github/workflows/build_mix.yml | 4 ++-- .github/workflows/build_paracross.yml | 4 ++-- .github/workflows/build_relay.yml | 4 ++-- .github/workflows/build_rgbx.yml | 4 ++-- .github/workflows/ci_dapps.yml | 4 ++-- .github/workflows/ci_fork_test.yml | 4 ++-- .github/workflows/ci_parachain_rollup.yml | 4 ++-- .github/workflows/manual_make_bin.yml | 4 ++-- .github/workflows/release.yml | 4 ++-- 13 files changed, 36 insertions(+), 36 deletions(-) diff --git a/.github/workflows/automake.yml b/.github/workflows/automake.yml index bc42b5b4d2..e16cf002f6 100644 --- a/.github/workflows/automake.yml +++ b/.github/workflows/automake.yml @@ -22,13 +22,13 @@ jobs: runs-on: ubuntu-22.04 steps: - name: Set up Golang env - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go - name: checkout repo - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 persist-credentials: false # <--- this diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3ea97fea38..e9fdcd8b3c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -5,10 +5,10 @@ jobs: check_fmt: runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version-file: 'go.mod' @@ -37,9 +37,9 @@ jobs: runs-on: ubuntu-22.04 steps: - name: checkout - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Set up Golang - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go @@ -53,9 +53,9 @@ jobs: runs-on: ubuntu-22.04 steps: - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Set up Golang - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go @@ -73,9 +73,9 @@ jobs: runs-on: ubuntu-22.04 steps: - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Set up Golang - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go @@ -91,9 +91,9 @@ jobs: runs-on: ubuntu-22.04 steps: - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Set up Golang - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go @@ -112,8 +112,8 @@ jobs: CGO_ENABLED: 1 steps: - - uses: actions/checkout@v3 - - uses: actions/setup-go@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 with: go-version-file: 'go.mod' - run: | diff --git a/.github/workflows/build_cross2eth.yml b/.github/workflows/build_cross2eth.yml index 6e8fdbdbca..79438838f6 100644 --- a/.github/workflows/build_cross2eth.yml +++ b/.github/workflows/build_cross2eth.yml @@ -7,9 +7,9 @@ jobs: runs-on: ubuntu-22.04 steps: - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Set up Golang - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go diff --git a/.github/workflows/build_evm.yml b/.github/workflows/build_evm.yml index 6ce7a2d84a..3de4a2789b 100644 --- a/.github/workflows/build_evm.yml +++ b/.github/workflows/build_evm.yml @@ -6,8 +6,8 @@ jobs: name: ci_evm runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 - - uses: actions/setup-go@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 with: go-version-file: 'go.mod' - name: deploy diff --git a/.github/workflows/build_mix.yml b/.github/workflows/build_mix.yml index 71e8257337..d7f33996fa 100644 --- a/.github/workflows/build_mix.yml +++ b/.github/workflows/build_mix.yml @@ -7,9 +7,9 @@ jobs: runs-on: ubuntu-22.04 steps: - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Set up Golang - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go diff --git a/.github/workflows/build_paracross.yml b/.github/workflows/build_paracross.yml index 194c0d0469..124ba6f9bd 100644 --- a/.github/workflows/build_paracross.yml +++ b/.github/workflows/build_paracross.yml @@ -7,9 +7,9 @@ jobs: runs-on: ubuntu-22.04 steps: - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Set up Golang - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go diff --git a/.github/workflows/build_relay.yml b/.github/workflows/build_relay.yml index 80f7a5c490..dae5b34626 100644 --- a/.github/workflows/build_relay.yml +++ b/.github/workflows/build_relay.yml @@ -6,9 +6,9 @@ jobs: name: ci_relay runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Golang - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go diff --git a/.github/workflows/build_rgbx.yml b/.github/workflows/build_rgbx.yml index c90b6492cc..08dff096c5 100644 --- a/.github/workflows/build_rgbx.yml +++ b/.github/workflows/build_rgbx.yml @@ -8,9 +8,9 @@ jobs: timeout-minutes: 90 steps: - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Set up Golang - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go diff --git a/.github/workflows/ci_dapps.yml b/.github/workflows/ci_dapps.yml index 7347af7b63..9100ab4d12 100644 --- a/.github/workflows/ci_dapps.yml +++ b/.github/workflows/ci_dapps.yml @@ -31,13 +31,13 @@ jobs: steps: - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: # bridgevmxgo 的 cmd/build.sh 用 git describe --tags 注入版本号 fetch-depth: 0 - name: Set up Golang - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go diff --git a/.github/workflows/ci_fork_test.yml b/.github/workflows/ci_fork_test.yml index 4a16395387..371628a44b 100644 --- a/.github/workflows/ci_fork_test.yml +++ b/.github/workflows/ci_fork_test.yml @@ -22,12 +22,12 @@ jobs: timeout-minutes: 120 steps: - name: checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 - name: Set up Golang - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go diff --git a/.github/workflows/ci_parachain_rollup.yml b/.github/workflows/ci_parachain_rollup.yml index 38837723bf..b1a0bddc5f 100644 --- a/.github/workflows/ci_parachain_rollup.yml +++ b/.github/workflows/ci_parachain_rollup.yml @@ -6,8 +6,8 @@ jobs: name: ci_parachain_rollup runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 - - uses: actions/setup-go@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 with: go-version-file: 'go.mod' - name: deploy diff --git a/.github/workflows/manual_make_bin.yml b/.github/workflows/manual_make_bin.yml index 95c04934b9..478e32615e 100644 --- a/.github/workflows/manual_make_bin.yml +++ b/.github/workflows/manual_make_bin.yml @@ -11,9 +11,9 @@ jobs: name: automake runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Golang env - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version-file: 'go.mod' id: go diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b9dc48fe3d..b9e81ccf45 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,11 +13,11 @@ jobs: steps: - name: checkout repo - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 persist-credentials: false # <--- this - - uses: actions/setup-go@v2 + - uses: actions/setup-go@v5 with: go-version-file: 'go.mod' - uses: actions/setup-node@v3 From 357f4861ea08ce93f90926f49df74eb51cab31db Mon Sep 17 00:00:00 2001 From: king Date: Wed, 2 Sep 2026 09:05:40 +0000 Subject: [PATCH 10/11] ci: deduplicate push/pull_request runs in all workflows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Same-repo branches previously ran the full job matrix twice per commit (once for push, once for pull_request synchronize). Adopt the standard dedup pattern: push triggers only on master, pull_request covers all PRs including forks. Behavior after merge is unchanged — master pushes still run every workflow. release.yml already used this pattern; automake.yml (workflow_dispatch) and ci_fork_test.yml (schedule) are unaffected. Co-Authored-By: Claude --- .github/workflows/build.yml | 5 ++++- .github/workflows/build_cross2eth.yml | 5 ++++- .github/workflows/build_evm.yml | 5 ++++- .github/workflows/build_mix.yml | 5 ++++- .github/workflows/build_paracross.yml | 5 ++++- .github/workflows/build_relay.yml | 5 ++++- .github/workflows/build_rgbx.yml | 5 ++++- .github/workflows/build_windows.yml | 5 ++++- .github/workflows/ci_dapps.yml | 5 ++++- .github/workflows/ci_parachain_rollup.yml | 5 ++++- .github/workflows/manual_make_bin.yml | 5 ++++- 11 files changed, 44 insertions(+), 11 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e9fdcd8b3c..d48f5eab62 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,5 +1,8 @@ name: ci_base -on: [push,pull_request] +on: + push: + branches: [ master ] + pull_request: jobs: check_fmt: diff --git a/.github/workflows/build_cross2eth.yml b/.github/workflows/build_cross2eth.yml index 79438838f6..5141e63aaf 100644 --- a/.github/workflows/build_cross2eth.yml +++ b/.github/workflows/build_cross2eth.yml @@ -1,5 +1,8 @@ name: ci_cross2eth -on: [push,pull_request] +on: + push: + branches: [ master ] + pull_request: jobs: ci_cross2eth: diff --git a/.github/workflows/build_evm.yml b/.github/workflows/build_evm.yml index 3de4a2789b..47b6fa2825 100644 --- a/.github/workflows/build_evm.yml +++ b/.github/workflows/build_evm.yml @@ -1,5 +1,8 @@ name: ci_evm -on: [push,pull_request] +on: + push: + branches: [ master ] + pull_request: jobs: ci_evm: diff --git a/.github/workflows/build_mix.yml b/.github/workflows/build_mix.yml index d7f33996fa..e5a124b4fd 100644 --- a/.github/workflows/build_mix.yml +++ b/.github/workflows/build_mix.yml @@ -1,5 +1,8 @@ name: ci_mix -on: [push,pull_request] +on: + push: + branches: [ master ] + pull_request: jobs: ci_mix: diff --git a/.github/workflows/build_paracross.yml b/.github/workflows/build_paracross.yml index 124ba6f9bd..8b6b4bec20 100644 --- a/.github/workflows/build_paracross.yml +++ b/.github/workflows/build_paracross.yml @@ -1,5 +1,8 @@ name: ci_paracross -on: [push,pull_request] +on: + push: + branches: [ master ] + pull_request: jobs: paracross: diff --git a/.github/workflows/build_relay.yml b/.github/workflows/build_relay.yml index dae5b34626..e52a3d7d63 100644 --- a/.github/workflows/build_relay.yml +++ b/.github/workflows/build_relay.yml @@ -1,5 +1,8 @@ name: ci_relay -on: [push,pull_request] +on: + push: + branches: [ master ] + pull_request: jobs: ci_relay: diff --git a/.github/workflows/build_rgbx.yml b/.github/workflows/build_rgbx.yml index 08dff096c5..781f6860f7 100644 --- a/.github/workflows/build_rgbx.yml +++ b/.github/workflows/build_rgbx.yml @@ -1,5 +1,8 @@ name: ci_rgbx -on: [push, pull_request] +on: + push: + branches: [ master ] + pull_request: jobs: ci_rgbx: diff --git a/.github/workflows/build_windows.yml b/.github/workflows/build_windows.yml index c02ef5f1c2..3a449783c8 100644 --- a/.github/workflows/build_windows.yml +++ b/.github/workflows/build_windows.yml @@ -1,5 +1,8 @@ name: build_windows -on: [push, pull_request] +on: + push: + branches: [ master ] + pull_request: jobs: build-windows: diff --git a/.github/workflows/ci_dapps.yml b/.github/workflows/ci_dapps.yml index 9100ab4d12..23ce7966c4 100644 --- a/.github/workflows/ci_dapps.yml +++ b/.github/workflows/ci_dapps.yml @@ -1,5 +1,8 @@ name: ci_dapps -on: [push, pull_request] +on: + push: + branches: [ master ] + pull_request: # 原 Jenkins ci-plugin (Jenkinsfile) 迁移而来。 # Jenkins 执行 `docker-compose-pre.sh run all`,即遍历 build/ci 下所有 diff --git a/.github/workflows/ci_parachain_rollup.yml b/.github/workflows/ci_parachain_rollup.yml index b1a0bddc5f..37ae8d1d01 100644 --- a/.github/workflows/ci_parachain_rollup.yml +++ b/.github/workflows/ci_parachain_rollup.yml @@ -1,5 +1,8 @@ name: ci_parachain_rollup -on: [push,pull_request] +on: + push: + branches: [ master ] + pull_request: jobs: paracross: diff --git a/.github/workflows/manual_make_bin.yml b/.github/workflows/manual_make_bin.yml index 478e32615e..d629276aa6 100644 --- a/.github/workflows/manual_make_bin.yml +++ b/.github/workflows/manual_make_bin.yml @@ -3,7 +3,10 @@ name: manually make bin for all branch # Controls when the action will run. Workflow runs when manually triggered using the UI # or API. -on: [push,pull_request] +on: + push: + branches: [ master ] + pull_request: # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: From f2cc11bcba1c2181635ce0cf93ffeb4e65ede66e Mon Sep 17 00:00:00 2001 From: king Date: Wed, 2 Sep 2026 10:52:58 +0000 Subject: [PATCH 11/11] ci: delete build_relay.yml, a pre-existing fake-green job Same class as the removed build_ticket.yml: relay/cmd/build.sh has had its OUT_DIR/relayd build section commented out since 2021 (739e84e44, upstream), so build/ci/relay is never created and `make docker-compose dapp=relay` only prints "dapp=relay not exist or is system dir" before returning 0. Relay's real coverage runs in build.yml's ci_base job via dapptest (relay/test-rpc.sh, copied by the still-active part of build.sh), so no replacement job is needed. This moves the item out of the PR's known leftovers. Co-Authored-By: Claude --- .github/workflows/build_relay.yml | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 .github/workflows/build_relay.yml diff --git a/.github/workflows/build_relay.yml b/.github/workflows/build_relay.yml deleted file mode 100644 index e52a3d7d63..0000000000 --- a/.github/workflows/build_relay.yml +++ /dev/null @@ -1,24 +0,0 @@ -name: ci_relay -on: - push: - branches: [ master ] - pull_request: - -jobs: - ci_relay: - name: ci_relay - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v4 - - name: Set up Golang - uses: actions/setup-go@v5 - with: - go-version-file: 'go.mod' - id: go - - name: set go env - run: export PATH=${PATH}:`go env GOPATH`/bin - - - name: deploy - run: | - make docker-compose dapp=relay - make docker-compose-down dapp=relay