From 9d118dcf07d5c66179b87a924d255d114a5842fb Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Wed, 13 Apr 2022 17:00:27 +0800 Subject: [PATCH 01/43] chore: add integration test workflow --- .github/workflows/integration.yml | 38 +++++++++++++++++++++++++++++ Makefile | 5 ++-- go.sum | 2 +- integration_test.sh | 3 ++- networks/demo/HTLT-cross-chain.exp | 2 +- networks/demo/HTLT-single-chain.exp | 2 +- networks/demo/add_key.exp | 2 +- networks/demo/cancel.exp | 2 +- networks/demo/claim.exp | 2 +- networks/demo/deposit.exp | 2 +- networks/demo/issue.exp | 2 +- networks/demo/issue_mini.exp | 2 +- networks/demo/list.exp | 2 +- networks/demo/list_mini.exp | 2 +- networks/demo/mint.exp | 2 +- networks/demo/multi_send.exp | 2 +- networks/demo/order.exp | 2 +- networks/demo/propose_list.exp | 2 +- networks/demo/recover.exp | 2 +- networks/demo/refund.exp | 2 +- networks/demo/send.exp | 2 +- networks/demo/set_account_flags.exp | 2 +- networks/demo/seturi.exp | 2 +- networks/demo/vote.exp | 2 +- 24 files changed, 64 insertions(+), 24 deletions(-) create mode 100644 .github/workflows/integration.yml diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml new file mode 100644 index 000000000..23db2ffed --- /dev/null +++ b/.github/workflows/integration.yml @@ -0,0 +1,38 @@ +name: integration-ci + +on: ["push", "pull_request", "workflow_dispatch"] + +jobs: + integration-test: + runs-on: ubuntu-latest + env: + GOPRIVATE: github.com/bnb-chain/* + GH_ACCESS_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }} + steps: + - uses: actions/checkout@v3 + - name: Setup go + uses: actions/setup-go@v3 + with: + go-version: 1.16 + - id: go-cache-paths + run: | + echo "::set-output name=go-build::$(go env GOCACHE)" + echo "::set-output name=go-mod::$(go env GOMODCACHE)" + - name: Checkout + uses: actions/checkout@v2 + - name: Go Build Cache + uses: actions/cache@v2 + with: + path: ${{ steps.go-cache-paths.outputs.go-build }} + key: ${{ runner.os }}-gobuild-${{ hashFiles('**/go.sum') }} + - name: Go Mod Cache + uses: actions/cache@v2 + with: + path: ${{ steps.go-cache-paths.outputs.go-mod }} + key: ${{ runner.os }}-gomod-${{ hashFiles('**/go.sum') }} + - run: sudo apt-get update -y && sudo apt-get install -y expect + - run: git config --global url.https://$GH_ACCESS_TOKEN@github.com/.insteadOf https://github.com/ + # used to debug workflow +# - name: Setup tmate session +# uses: mxschmitt/action-tmate@v3 + - run: make integration_test diff --git a/Makefile b/Makefile index c05a0d951..6053b4baa 100644 --- a/Makefile +++ b/Makefile @@ -152,8 +152,9 @@ lint: ### Testing get_tools: - @echo "--> Installing tools" - ./scripts/get_tools.sh + @echo "--> skip Installing tools" +# @echo "--> Installing tools" +# ./scripts/get_tools.sh test: make set_with_deadlock diff --git a/go.sum b/go.sum index c412a3b4b..ee123c690 100644 --- a/go.sum +++ b/go.sum @@ -44,7 +44,7 @@ github.com/btcsuite/btcd v0.0.0-20190115013929-ed77733ec07d/go.mod h1:d3C0AkH6BR github.com/btcsuite/btcd v0.0.0-20190213025234-306aecffea32/go.mod h1:DrZx5ec/dmnfpw9KyYoQyYo7d0KEvTkk/5M/vbZjAr8= github.com/btcsuite/btcd v0.0.0-20190523000118-16327141da8c/go.mod h1:3J08xEfcugPacsc34/LKRU2yO7YmuT8yt28J8k2+rrI= github.com/btcsuite/btcd v0.0.0-20190629003639-c26ffa870fd8/go.mod h1:3J08xEfcugPacsc34/LKRU2yO7YmuT8yt28J8k2+rrI= -github.com/btcsuite/btcd v0.20.0-beta h1:PamBMopnHxO2nEIsU89ibVVnqnXR2yFTgGNc+PdG68o= +github.com/btcsuite/btcd v0.20.0-beta h1:DnZGUjFbRkpytojHWwy6nfUSA7vFrzWXDLpFNzt74ZA= github.com/btcsuite/btcd v0.20.0-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= github.com/btcsuite/btcutil v0.0.0-20180706230648-ab6388e0c60a/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= diff --git a/integration_test.sh b/integration_test.sh index 74f55cffc..83d391ca2 100755 --- a/integration_test.sh +++ b/integration_test.sh @@ -1,5 +1,7 @@ #!/bin/bash +set -ex + cd ./build if [ $? -ne 0 ]; then echo "path build does not exists" @@ -65,7 +67,6 @@ function check_operation() { secret=$(prepare_node) - result=$(expect ./recover.exp "${secret}" "alice" true) check_operation "Recover Key" "${result}" "${keys_operation_words}" diff --git a/networks/demo/HTLT-cross-chain.exp b/networks/demo/HTLT-cross-chain.exp index 3dcd33ec5..c16d5329b 100644 --- a/networks/demo/HTLT-cross-chain.exp +++ b/networks/demo/HTLT-cross-chain.exp @@ -17,4 +17,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/HTLT-single-chain.exp b/networks/demo/HTLT-single-chain.exp index 0090643ea..ef500d2db 100644 --- a/networks/demo/HTLT-single-chain.exp +++ b/networks/demo/HTLT-single-chain.exp @@ -16,4 +16,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/add_key.exp b/networks/demo/add_key.exp index bf2aca78c..e46e114c0 100755 --- a/networks/demo/add_key.exp +++ b/networks/demo/add_key.exp @@ -9,4 +9,4 @@ set timeout 30 send "12345678\r" expect "Repeat*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/cancel.exp b/networks/demo/cancel.exp index 55232b21d..3a60498f8 100755 --- a/networks/demo/cancel.exp +++ b/networks/demo/cancel.exp @@ -14,4 +14,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/claim.exp b/networks/demo/claim.exp index 89359378f..220b2272c 100644 --- a/networks/demo/claim.exp +++ b/networks/demo/claim.exp @@ -14,4 +14,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/deposit.exp b/networks/demo/deposit.exp index 8deb57695..777041835 100644 --- a/networks/demo/deposit.exp +++ b/networks/demo/deposit.exp @@ -14,4 +14,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/issue.exp b/networks/demo/issue.exp index 9837b3ccb..a1d8890ff 100755 --- a/networks/demo/issue.exp +++ b/networks/demo/issue.exp @@ -16,4 +16,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/issue_mini.exp b/networks/demo/issue_mini.exp index 39a86f5b3..e488f6968 100755 --- a/networks/demo/issue_mini.exp +++ b/networks/demo/issue_mini.exp @@ -18,4 +18,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/list.exp b/networks/demo/list.exp index 454953ba9..2b4e7121c 100755 --- a/networks/demo/list.exp +++ b/networks/demo/list.exp @@ -16,4 +16,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/list_mini.exp b/networks/demo/list_mini.exp index 58cf6f515..252e63f0a 100755 --- a/networks/demo/list_mini.exp +++ b/networks/demo/list_mini.exp @@ -16,4 +16,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/mint.exp b/networks/demo/mint.exp index c1528d9a5..438b2f78f 100644 --- a/networks/demo/mint.exp +++ b/networks/demo/mint.exp @@ -14,4 +14,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/multi_send.exp b/networks/demo/multi_send.exp index 4e62bf174..1fe6daf0c 100755 --- a/networks/demo/multi_send.exp +++ b/networks/demo/multi_send.exp @@ -10,4 +10,4 @@ set timeout 30 spawn ./bnbcli token multi-send --home $home --from $from --chain-id=$chain_id --transfers $tx --memo $memo expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/order.exp b/networks/demo/order.exp index 74999be30..61b257782 100755 --- a/networks/demo/order.exp +++ b/networks/demo/order.exp @@ -17,4 +17,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/propose_list.exp b/networks/demo/propose_list.exp index e5229a591..0559e4a2b 100755 --- a/networks/demo/propose_list.exp +++ b/networks/demo/propose_list.exp @@ -16,4 +16,4 @@ set timeout 30 spawn ./bnbcli gov submit-list-proposal --chain-id ${chain_id} --from ${from} --deposit ${deposit} --base-asset-symbol ${base_asset} --quote-asset-symbol ${quote_asset} --init-price ${init_price} --title ${title} --description ${description} --home ${home} --expire-time ${expire_time} --voting-period ${voting_period} expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/recover.exp b/networks/demo/recover.exp index 7e51eaa08..6aa0a57eb 100755 --- a/networks/demo/recover.exp +++ b/networks/demo/recover.exp @@ -18,4 +18,4 @@ set timeout 30 send "12345678\r" expect "Enter*" send "${secret}\r" -interact +expect eof diff --git a/networks/demo/refund.exp b/networks/demo/refund.exp index c9df3d237..42a879e91 100644 --- a/networks/demo/refund.exp +++ b/networks/demo/refund.exp @@ -13,4 +13,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/send.exp b/networks/demo/send.exp index c4ff1020c..fa164b5a2 100755 --- a/networks/demo/send.exp +++ b/networks/demo/send.exp @@ -11,4 +11,4 @@ set timeout 30 spawn ./bnbcli send --home $home --from $from --chain-id=$chain_id --amount $amount --to $to --memo $memo expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/set_account_flags.exp b/networks/demo/set_account_flags.exp index 48f18bfb3..929dc8b54 100644 --- a/networks/demo/set_account_flags.exp +++ b/networks/demo/set_account_flags.exp @@ -13,4 +13,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/seturi.exp b/networks/demo/seturi.exp index c1528d9a5..438b2f78f 100644 --- a/networks/demo/seturi.exp +++ b/networks/demo/seturi.exp @@ -14,4 +14,4 @@ set timeout 30 } expect "Password*" send "12345678\r" -interact +expect eof diff --git a/networks/demo/vote.exp b/networks/demo/vote.exp index 66e156b64..175ddadd9 100755 --- a/networks/demo/vote.exp +++ b/networks/demo/vote.exp @@ -10,4 +10,4 @@ set timeout 30 spawn ./bnbcli gov vote --from ${from} --chain-id ${chain_id} --proposal-id ${proposal_id} --option ${option} --home ${home} expect "Password*" send "12345678\r" -interact +expect eof From b8b5dcd66b14550df1aeaf1361cc6dd529ad96d8 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Wed, 13 Apr 2022 17:22:05 +0800 Subject: [PATCH 02/43] add build and test in workflow --- .github/workflows/integration.yml | 2 + Makefile | 5 +-- scripts/get_tools.sh | 73 ++++++++++++++++--------------- 3 files changed, 42 insertions(+), 38 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 23db2ffed..eb45cce6b 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -35,4 +35,6 @@ jobs: # used to debug workflow # - name: Setup tmate session # uses: mxschmitt/action-tmate@v3 + - run: make build + - run: make test - run: make integration_test diff --git a/Makefile b/Makefile index 6053b4baa..c05a0d951 100644 --- a/Makefile +++ b/Makefile @@ -152,9 +152,8 @@ lint: ### Testing get_tools: - @echo "--> skip Installing tools" -# @echo "--> Installing tools" -# ./scripts/get_tools.sh + @echo "--> Installing tools" + ./scripts/get_tools.sh test: make set_with_deadlock diff --git a/scripts/get_tools.sh b/scripts/get_tools.sh index ec0ab02e3..3870b1b43 100755 --- a/scripts/get_tools.sh +++ b/scripts/get_tools.sh @@ -5,41 +5,44 @@ set -e # specific git hash. ## check if GOPATH is set -if [ -z ${GOPATH+x} ]; then - echo "please set GOPATH (https://github.com/golang/go/wiki/SettingGOPATH)" - exit 1 -fi - -mkdir -p "$GOPATH/src/github.com" -cd "$GOPATH/src/github.com" || exit 1 - -installFromGithub() { - repo=$1 - commit=$2 - # optional - subdir=$3 - echo "--> Installing $repo ($commit)..." - if [ ! -d "$repo" ]; then - mkdir -p "$repo" - git clone "https://github.com/$repo.git" "$repo" - fi - if [ ! -z ${subdir+x} ] && [ ! -d "$repo/$subdir" ]; then - echo "ERROR: no such directory $repo/$subdir" - exit 1 - fi - pushd "$repo" && \ - git fetch origin && \ - git checkout -q "$commit" && \ - if [ ! -z ${subdir+x} ]; then cd "$subdir" || exit 1; fi && \ - go install && \ - if [ ! -z ${subdir+x} ]; then cd - || exit 1; fi && \ - popd || exit 1 - echo "--> Done" - echo "" -} +#if [ -z ${GOPATH+x} ]; then +# echo "please set GOPATH (https://github.com/golang/go/wiki/SettingGOPATH)" +# exit 1 +#fi +# +#mkdir -p "$GOPATH/src/github.com" +#cd "$GOPATH/src/github.com" || exit 1 +# +#installFromGithub() { +# repo=$1 +# commit=$2 +# # optional +# subdir=$3 +# echo "--> Installing $repo ($commit)..." +# if [ ! -d "$repo" ]; then +# mkdir -p "$repo" +# git clone "https://github.com/$repo.git" "$repo" +# fi +# if [ ! -z ${subdir+x} ] && [ ! -d "$repo/$subdir" ]; then +# echo "ERROR: no such directory $repo/$subdir" +# exit 1 +# fi +# pushd "$repo" && \ +# git fetch origin && \ +# git checkout -q "$commit" && \ +# if [ ! -z ${subdir+x} ]; then cd "$subdir" || exit 1; fi && \ +# go install && \ +# if [ ! -z ${subdir+x} ]; then cd - || exit 1; fi && \ +# popd || exit 1 +# echo "--> Done" +# echo "" +#} ######################## COMMON TOOLS ######################################## ## XXX: https://github.com/tendermint/tendermint/issues/3242 -installFromGithub petermattis/goid b0b1615b78e5ee59739545bb38426383b2cda4c9 -installFromGithub sasha-s/go-deadlock d68e2bc52ae3291765881b9056f2c1527f245f1e -go get golang.org/x/tools/cmd/goimports +#installFromGithub petermattis/goid b0b1615b78e5ee59739545bb38426383b2cda4c9 +#installFromGithub sasha-s/go-deadlock d68e2bc52ae3291765881b9056f2c1527f245f1e +go get github.com/petermattis/goid@b0b1615b78e5ee59739545bb38426383b2cda4c9 +go get github.com/sasha-s/go-deadlock@d68e2bc52ae3291765881b9056f2c1527f245f1e +go mod download golang.org/x/tools +go install golang.org/x/tools/cmd/goimports From 39855d11753f9b1e5cdd534d46e6685684616679 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Wed, 13 Apr 2022 17:40:09 +0800 Subject: [PATCH 03/43] optimize workflow cache --- .github/workflows/integration.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index eb45cce6b..c6d502eb9 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -25,11 +25,15 @@ jobs: with: path: ${{ steps.go-cache-paths.outputs.go-build }} key: ${{ runner.os }}-gobuild-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-gobuild- - name: Go Mod Cache uses: actions/cache@v2 with: path: ${{ steps.go-cache-paths.outputs.go-mod }} key: ${{ runner.os }}-gomod-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-gomod- - run: sudo apt-get update -y && sudo apt-get install -y expect - run: git config --global url.https://$GH_ACCESS_TOKEN@github.com/.insteadOf https://github.com/ # used to debug workflow From bca49efb08e1a089a39513c16a8b43aea0d10aa6 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Wed, 13 Apr 2022 17:43:39 +0800 Subject: [PATCH 04/43] skip error file --- .github/workflows/integration.yml | 2 +- app/{app_paramhub_test.go => app_paramhub_test.go.bak} | 0 app/{app_pub_test.go => app_pub_test.go.bak} | 0 go.mod | 2 ++ go.sum | 5 +++++ 5 files changed, 8 insertions(+), 1 deletion(-) rename app/{app_paramhub_test.go => app_paramhub_test.go.bak} (100%) rename app/{app_pub_test.go => app_pub_test.go.bak} (100%) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index c6d502eb9..010d14c18 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -40,5 +40,5 @@ jobs: # - name: Setup tmate session # uses: mxschmitt/action-tmate@v3 - run: make build - - run: make test - run: make integration_test + - run: make test diff --git a/app/app_paramhub_test.go b/app/app_paramhub_test.go.bak similarity index 100% rename from app/app_paramhub_test.go rename to app/app_paramhub_test.go.bak diff --git a/app/app_pub_test.go b/app/app_pub_test.go.bak similarity index 100% rename from app/app_pub_test.go rename to app/app_pub_test.go.bak diff --git a/go.mod b/go.mod index 71140fd71..856ac6a7b 100644 --- a/go.mod +++ b/go.mod @@ -14,8 +14,10 @@ require ( github.com/linkedin/goavro v0.0.0-20180427201934-fa8f6a30176c github.com/mitchellh/go-homedir v1.1.0 github.com/natefinch/lumberjack v2.0.0+incompatible + github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect github.com/pkg/errors v0.8.1 github.com/prometheus/client_golang v1.1.0 + github.com/sasha-s/go-deadlock v0.2.1-0.20180822072021-d68e2bc52ae3 // indirect github.com/spf13/cobra v0.0.5 github.com/spf13/viper v1.4.0 github.com/stretchr/testify v1.4.0 diff --git a/go.sum b/go.sum index ee123c690..63dedebeb 100644 --- a/go.sum +++ b/go.sum @@ -403,6 +403,8 @@ github.com/otiai10/primes v0.0.0-20180210170552-f6d2a1ba97c4/go.mod h1:UmSP7QeU3 github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.4.0 h1:u3Z1r+oOXJIkxqw34zVhyPgjBsm6X2wn21NWs/HfSeg= github.com/pelletier/go-toml v1.4.0/go.mod h1:PN7xzY2wHTK0K9p34ErDQMlFxa51Fk0OUruD3k1mMwo= +github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 h1:q2e307iGHPdTGp0hoxKjt1H5pDo6utceo3dQVK3I5XQ= +github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= github.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2/go.mod h1:iIss55rKnNBTvrwdmkUpLnDpZoAHvWaiq5+iMmen4AE= github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= @@ -440,6 +442,8 @@ github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6So github.com/rs/cors v1.6.0 h1:G9tHG9lebljV9mfp9SNPDL36nCDxmo3zTlAf1YgvzmI= github.com/rs/cors v1.6.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/sasha-s/go-deadlock v0.2.1-0.20180822072021-d68e2bc52ae3 h1:PFrDl/KPigLkWkRl/AqIztEvC/iSnwKmTCy9qbqgevw= +github.com/sasha-s/go-deadlock v0.2.1-0.20180822072021-d68e2bc52ae3/go.mod h1:StQn567HiB1fF2yJ44N9au7wOhrPS3iZqiDbRupzT10= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/smola/gocompat v0.2.0/go.mod h1:1B0MlxbmoZNo3h8guHp8HztB3BSYR5itql9qtVc0ypY= github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa/go.mod h1:oJyF+mSPHbB5mVY2iO9KV3pTt/QbIkGaO8gQ2WrDbP4= @@ -572,6 +576,7 @@ golang.org/x/tools v0.0.0-20181130052023-1c3d964395ce/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135 h1:5Beo0mZN8dRzgrMMkDp0jc8YXQKx9DiJ2k1dkvGsn5A= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898 h1:/atklqdjdhuosWIl6AIbOeHJjicWYPqR9bpxqxYG2pA= From 411275ac5f80fd3412d62c08958907387e908aae Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Thu, 21 Apr 2022 11:00:50 +0800 Subject: [PATCH 05/43] feat: add release workflow --- .github/workflows/release.yml | 181 ++++++++++++++++++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 .github/workflows/release.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 000000000..de1314ea7 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,181 @@ +name: Release + +#on: +# push: +# # Publish `v1.2.3` tags as releases. +# tags: +# - v* + +on: ["push", "pull_request", "workflow_dispatch"] + +jobs: + build: + name: Build Release + strategy: + matrix: + go-version: [1.16.x] + os: [ubuntu-18.04, macos-11, windows-2019] + env: + GOPRIVATE: github.com/bnb-chain/* + GH_ACCESS_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }} + runs-on: ${{ matrix.os }} + steps: + - name: Checkout Code + uses: actions/checkout@v2 + + - name: Install Go + uses: actions/setup-go@v2 + with: + go-version: ${{ matrix.go-version }} + + - uses: actions/cache@v2 + with: + # In order: + # * Module download cache + # * Build cache (Linux) + # * Build cache (Mac) + # * Build cache (Windows) + path: | + ~/go/pkg/mod + ~/.cache/go-build + ~/Library/Caches/go-build + %LocalAppData%\go-build + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + # ============================== + # Linux/Macos/Windows Build + # ============================== + + - name: Build Binary for ${{matrix.os}} + run: make build + + # ============================== + # Upload artifacts + # ============================== + + - name: Upload Linux Build + uses: actions/upload-artifact@v2 + if: matrix.os == 'ubuntu-18.04' + with: + name: linux + path: ./build + + - name: Upload MacOS Build + uses: actions/upload-artifact@v2 + if: matrix.os == 'macos-11' + with: + name: macos + path: ./build + + - name: Upload Windows Build + uses: actions/upload-artifact@v2 + if: matrix.os == 'windows-2019' + with: + name: windows + path: ./build + + release: + name: Release + needs: build + runs-on: ubuntu-18.04 + steps: + - name: Set Env + run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV + + - name: Checkout Code + uses: actions/checkout@v2 + + # ============================== + # Download artifacts + # ============================== + + - name: Download Artifacts + uses: actions/download-artifact@v2 + with: + name: linux + path: ./linux + + - name: Download Artifacts + uses: actions/download-artifact@v2 + with: + name: macos + path: ./macos + + - name: Download Artifacts + uses: actions/download-artifact@v2 + with: + name: windows + path: ./windows + + - run: zip -r linux.zip linux + - run: zip -r macos.zip macos + - run: zip -r windows.zip windows + +# - name: Download Config File +# run: | +# . ./.github/release.env +# echo "mainnet.zip url: $MAINNET_FILE_URL" +# echo "testnet.zip url: $TESTNET_FILE_URL" +# curl -L $MAINNET_FILE_URL -o ./mainnet.zip +# curl -L $TESTNET_FILE_URL -o ./testnet.zip + + # ============================== + # Create release + # ============================== +# - name: Generate Change Log +# id: changelog +# run: | +# chmod 755 ./.github/generate_change_log.sh +# CHANGELOG=$(./.github/generate_change_log.sh ${{ env.RELEASE_VERSION}}) +# +# echo "CHANGELOG<> $GITHUB_ENV +# echo "$CHANGELOG" >> $GITHUB_ENV +# echo "EOF" >> $GITHUB_ENV + + - name: Create Release + id: create_release + uses: actions/create-release@latest + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token + with: + tag_name: ${{ github.ref }} + release_name: ${{ github.ref }} +# body: | +# ${{ env.CHANGELOG }} + draft: false + prerelease: false + + # Check downloaded files + - run: ls + + - name: Upload Release Asset - Linux + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps + asset_path: ./linux.zip + asset_name: linux.zip + asset_content_type: application/octet-stream + + - name: Upload Release Asset - MacOS + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps + asset_path: ./macos.zip + asset_name: macos.zip + asset_content_type: application/octet-stream + + - name: Upload Release Asset - Windows + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps + asset_path: ./windows.zip + asset_name: windows.zip + asset_content_type: application/octet-stream From e8dc66e3be6e2cce1e87cbd19295665d3d2b67c7 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Thu, 21 Apr 2022 14:52:31 +0800 Subject: [PATCH 06/43] fix release workflow --- .github/workflows/release.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index de1314ea7..07895023c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -44,6 +44,8 @@ jobs: restore-keys: | ${{ runner.os }}-go- + - run: git config --global url.https://$GH_ACCESS_TOKEN@github.com/.insteadOf https://github.com/ + # ============================== # Linux/Macos/Windows Build # ============================== From 7e06abe51a3ddd3c6308e0b77961eeb969a5a9f5 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Thu, 21 Apr 2022 14:56:44 +0800 Subject: [PATCH 07/43] disable window to debug --- .github/workflows/release.yml | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 07895023c..ef099cdc9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -14,7 +14,8 @@ jobs: strategy: matrix: go-version: [1.16.x] - os: [ubuntu-18.04, macos-11, windows-2019] + os: [ubuntu-18.04, macos-11] +# os: [ubuntu-18.04, macos-11, windows-2019] env: GOPRIVATE: github.com/bnb-chain/* GH_ACCESS_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }} @@ -105,15 +106,15 @@ jobs: name: macos path: ./macos - - name: Download Artifacts - uses: actions/download-artifact@v2 - with: - name: windows - path: ./windows +# - name: Download Artifacts +# uses: actions/download-artifact@v2 +# with: +# name: windows +# path: ./windows - run: zip -r linux.zip linux - run: zip -r macos.zip macos - - run: zip -r windows.zip windows +# - run: zip -r windows.zip windows # - name: Download Config File # run: | @@ -171,13 +172,13 @@ jobs: asset_path: ./macos.zip asset_name: macos.zip asset_content_type: application/octet-stream - - - name: Upload Release Asset - Windows - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps - asset_path: ./windows.zip - asset_name: windows.zip - asset_content_type: application/octet-stream +# +# - name: Upload Release Asset - Windows +# uses: actions/upload-release-asset@v1 +# env: +# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} +# with: +# upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps +# asset_path: ./windows.zip +# asset_name: windows.zip +# asset_content_type: application/octet-stream From 4f8cd2adc8fb78036a5849e00e06718f912e54a9 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Thu, 21 Apr 2022 15:17:46 +0800 Subject: [PATCH 08/43] test release name --- .github/workflows/release.yml | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ef099cdc9..e195a8928 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -14,7 +14,7 @@ jobs: strategy: matrix: go-version: [1.16.x] - os: [ubuntu-18.04, macos-11] + os: [ubuntu-18.04] # os: [ubuntu-18.04, macos-11, windows-2019] env: GOPRIVATE: github.com/bnb-chain/* @@ -84,9 +84,9 @@ jobs: needs: build runs-on: ubuntu-18.04 steps: - - name: Set Env - run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV - +# - name: Set Env +# run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV +# - name: Checkout Code uses: actions/checkout@v2 @@ -100,11 +100,11 @@ jobs: name: linux path: ./linux - - name: Download Artifacts - uses: actions/download-artifact@v2 - with: - name: macos - path: ./macos +# - name: Download Artifacts +# uses: actions/download-artifact@v2 +# with: +# name: macos +# path: ./macos # - name: Download Artifacts # uses: actions/download-artifact@v2 @@ -113,7 +113,7 @@ jobs: # path: ./windows - run: zip -r linux.zip linux - - run: zip -r macos.zip macos +# - run: zip -r macos.zip macos # - run: zip -r windows.zip windows # - name: Download Config File @@ -143,8 +143,8 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token with: - tag_name: ${{ github.ref }} - release_name: ${{ github.ref }} + tag_name: ${{ github.ref_name }}-${{ github.sha }} + release_name: ${{ github.ref_name }}-${{ github.sha }} # body: | # ${{ env.CHANGELOG }} draft: false From ffa73b17525dcc43de953175fe475f0ba2890d20 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Thu, 21 Apr 2022 15:34:03 +0800 Subject: [PATCH 09/43] fix release tag --- .github/workflows/release.yml | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e195a8928..3acf75c69 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,12 +1,11 @@ name: Release -#on: -# push: -# # Publish `v1.2.3` tags as releases. -# tags: -# - v* - -on: ["push", "pull_request", "workflow_dispatch"] +on: + push: + # Publish `v1.2.3` tags as releases. + tags: + - v* + - t* jobs: build: @@ -143,8 +142,8 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token with: - tag_name: ${{ github.ref_name }}-${{ github.sha }} - release_name: ${{ github.ref_name }}-${{ github.sha }} + tag_name: ${{ github.ref_name }} + release_name: ${{ github.ref_name }} # body: | # ${{ env.CHANGELOG }} draft: false From a759bdacf1e21f52cce240fe6e3114802d881a3a Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Thu, 21 Apr 2022 15:38:40 +0800 Subject: [PATCH 10/43] fix release tag --- .github/workflows/release.yml | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3acf75c69..86a91b59f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -162,15 +162,15 @@ jobs: asset_name: linux.zip asset_content_type: application/octet-stream - - name: Upload Release Asset - MacOS - uses: actions/upload-release-asset@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps - asset_path: ./macos.zip - asset_name: macos.zip - asset_content_type: application/octet-stream +# - name: Upload Release Asset - MacOS +# uses: actions/upload-release-asset@v1 +# env: +# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} +# with: +# upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps +# asset_path: ./macos.zip +# asset_name: macos.zip +# asset_content_type: application/octet-stream # # - name: Upload Release Asset - Windows # uses: actions/upload-release-asset@v1 From 7294c0cf736db8bad7dd85e0c7c26c5b2a4324e4 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Thu, 21 Apr 2022 15:55:11 +0800 Subject: [PATCH 11/43] add macos --- .github/workflows/release.yml | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 86a91b59f..ae623d4bf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -99,11 +99,11 @@ jobs: name: linux path: ./linux -# - name: Download Artifacts -# uses: actions/download-artifact@v2 -# with: -# name: macos -# path: ./macos + - name: Download Artifacts + uses: actions/download-artifact@v2 + with: + name: macos + path: ./macos # - name: Download Artifacts # uses: actions/download-artifact@v2 @@ -112,7 +112,7 @@ jobs: # path: ./windows - run: zip -r linux.zip linux -# - run: zip -r macos.zip macos + - run: zip -r macos.zip macos # - run: zip -r windows.zip windows # - name: Download Config File @@ -159,19 +159,19 @@ jobs: with: upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps asset_path: ./linux.zip - asset_name: linux.zip + asset_name: bnbchain-linux-${{ github.ref_name }}.zip + asset_content_type: application/octet-stream + + - name: Upload Release Asset - MacOS + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps + asset_path: ./macos.zip + asset_name: bnbchain-macos-${{ github.ref_name }}.zip asset_content_type: application/octet-stream -# - name: Upload Release Asset - MacOS -# uses: actions/upload-release-asset@v1 -# env: -# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} -# with: -# upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps -# asset_path: ./macos.zip -# asset_name: macos.zip -# asset_content_type: application/octet-stream -# # - name: Upload Release Asset - Windows # uses: actions/upload-release-asset@v1 # env: From 5e6f02f2a083ca371d2c2ae02a385ada7eff488b Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Thu, 21 Apr 2022 16:20:15 +0800 Subject: [PATCH 12/43] fix macos --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ae623d4bf..b7556c7f1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,7 +13,7 @@ jobs: strategy: matrix: go-version: [1.16.x] - os: [ubuntu-18.04] + os: [ubuntu-18.04, macos-11] # os: [ubuntu-18.04, macos-11, windows-2019] env: GOPRIVATE: github.com/bnb-chain/* From efa5369d461ef345d0de4a3caf6b29525daf8ce5 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Thu, 21 Apr 2022 22:22:43 +0800 Subject: [PATCH 13/43] fix make test --- Makefile | 4 ++-- plugins/api/handlers/simulate.go | 5 +++-- scripts/get_tools.sh | 3 +-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 3d19c9b28..9ccd16ead 100644 --- a/Makefile +++ b/Makefile @@ -80,7 +80,7 @@ define buildwindows endef -build: get_tools +build: ifeq ($(OS),Windows_NT) $(call buildwindows) else @@ -155,7 +155,7 @@ get_tools: @echo "--> Installing tools" ./scripts/get_tools.sh -test: +test: get_tools make set_with_deadlock make test_unit make test_race diff --git a/plugins/api/handlers/simulate.go b/plugins/api/handlers/simulate.go index 8474cfa7a..adca24a0d 100644 --- a/plugins/api/handlers/simulate.go +++ b/plugins/api/handlers/simulate.go @@ -3,11 +3,12 @@ package handlers import ( "encoding/hex" "fmt" - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" "io" "net/http" + "github.com/cosmos/cosmos-sdk/client/context" + sdk "github.com/cosmos/cosmos-sdk/types" + cctx "github.com/bnb-chain/node/common/client/context" "github.com/bnb-chain/node/wire" ) diff --git a/scripts/get_tools.sh b/scripts/get_tools.sh index 3870b1b43..6a0de1404 100755 --- a/scripts/get_tools.sh +++ b/scripts/get_tools.sh @@ -44,5 +44,4 @@ set -e #installFromGithub sasha-s/go-deadlock d68e2bc52ae3291765881b9056f2c1527f245f1e go get github.com/petermattis/goid@b0b1615b78e5ee59739545bb38426383b2cda4c9 go get github.com/sasha-s/go-deadlock@d68e2bc52ae3291765881b9056f2c1527f245f1e -go mod download golang.org/x/tools -go install golang.org/x/tools/cmd/goimports +go install golang.org/x/tools/cmd/goimports@latest From 70b8eee337f0d2980d0e7095719b990f042b3a07 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Thu, 21 Apr 2022 22:51:09 +0800 Subject: [PATCH 14/43] remove windows, zip before upload --- .github/workflows/release.yml | 59 +++++------------------------------ 1 file changed, 7 insertions(+), 52 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b7556c7f1..248f187ad 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -14,7 +14,6 @@ jobs: matrix: go-version: [1.16.x] os: [ubuntu-18.04, macos-11] -# os: [ubuntu-18.04, macos-11, windows-2019] env: GOPRIVATE: github.com/bnb-chain/* GH_ACCESS_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }} @@ -52,6 +51,8 @@ jobs: - name: Build Binary for ${{matrix.os}} run: make build + - run: mv build bnbchain-binaries + - run: zip -r bnbchain-binaries.zip bnbchain-binaries # ============================== # Upload artifacts @@ -62,30 +63,27 @@ jobs: if: matrix.os == 'ubuntu-18.04' with: name: linux - path: ./build + path: ./bnbchain-binaries.zip - name: Upload MacOS Build uses: actions/upload-artifact@v2 if: matrix.os == 'macos-11' with: name: macos - path: ./build + path: ./bnbchain-binaries.zip - name: Upload Windows Build uses: actions/upload-artifact@v2 if: matrix.os == 'windows-2019' with: name: windows - path: ./build + path: ./bnbchain-binaries.zip release: name: Release needs: build runs-on: ubuntu-18.04 steps: -# - name: Set Env -# run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV -# - name: Checkout Code uses: actions/checkout@v2 @@ -97,44 +95,13 @@ jobs: uses: actions/download-artifact@v2 with: name: linux - path: ./linux + path: ./linux.zip - name: Download Artifacts uses: actions/download-artifact@v2 with: name: macos - path: ./macos - -# - name: Download Artifacts -# uses: actions/download-artifact@v2 -# with: -# name: windows -# path: ./windows - - - run: zip -r linux.zip linux - - run: zip -r macos.zip macos -# - run: zip -r windows.zip windows - -# - name: Download Config File -# run: | -# . ./.github/release.env -# echo "mainnet.zip url: $MAINNET_FILE_URL" -# echo "testnet.zip url: $TESTNET_FILE_URL" -# curl -L $MAINNET_FILE_URL -o ./mainnet.zip -# curl -L $TESTNET_FILE_URL -o ./testnet.zip - - # ============================== - # Create release - # ============================== -# - name: Generate Change Log -# id: changelog -# run: | -# chmod 755 ./.github/generate_change_log.sh -# CHANGELOG=$(./.github/generate_change_log.sh ${{ env.RELEASE_VERSION}}) -# -# echo "CHANGELOG<> $GITHUB_ENV -# echo "$CHANGELOG" >> $GITHUB_ENV -# echo "EOF" >> $GITHUB_ENV + path: ./macos.zip - name: Create Release id: create_release @@ -144,8 +111,6 @@ jobs: with: tag_name: ${{ github.ref_name }} release_name: ${{ github.ref_name }} -# body: | -# ${{ env.CHANGELOG }} draft: false prerelease: false @@ -171,13 +136,3 @@ jobs: asset_path: ./macos.zip asset_name: bnbchain-macos-${{ github.ref_name }}.zip asset_content_type: application/octet-stream - -# - name: Upload Release Asset - Windows -# uses: actions/upload-release-asset@v1 -# env: -# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} -# with: -# upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps -# asset_path: ./windows.zip -# asset_name: windows.zip -# asset_content_type: application/octet-stream From a0d9c2b7f9ef2ceaea46a7829e13ddf7d19ae7ba Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Thu, 21 Apr 2022 22:52:28 +0800 Subject: [PATCH 15/43] remove build in integration ci --- .github/workflows/integration.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 010d14c18..31eb2828e 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -39,6 +39,5 @@ jobs: # used to debug workflow # - name: Setup tmate session # uses: mxschmitt/action-tmate@v3 - - run: make build - run: make integration_test - run: make test From 7262ff360b1ce0a1d39c548f3c78630f3b5372ec Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 10:51:38 +0800 Subject: [PATCH 16/43] update integration --- .github/workflows/integration.yml | 28 ++++++++-------------------- .github/workflows/release.yml | 1 - 2 files changed, 8 insertions(+), 21 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 31eb2828e..6b7920ba2 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -5,37 +5,25 @@ on: ["push", "pull_request", "workflow_dispatch"] jobs: integration-test: runs-on: ubuntu-latest - env: - GOPRIVATE: github.com/bnb-chain/* - GH_ACCESS_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }} steps: - uses: actions/checkout@v3 - name: Setup go uses: actions/setup-go@v3 with: go-version: 1.16 - - id: go-cache-paths - run: | - echo "::set-output name=go-build::$(go env GOCACHE)" - echo "::set-output name=go-mod::$(go env GOMODCACHE)" - name: Checkout uses: actions/checkout@v2 - - name: Go Build Cache - uses: actions/cache@v2 + - uses: actions/cache@v2 with: - path: ${{ steps.go-cache-paths.outputs.go-build }} - key: ${{ runner.os }}-gobuild-${{ hashFiles('**/go.sum') }} + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} restore-keys: | - ${{ runner.os }}-gobuild- - - name: Go Mod Cache - uses: actions/cache@v2 - with: - path: ${{ steps.go-cache-paths.outputs.go-mod }} - key: ${{ runner.os }}-gomod-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-gomod- + ${{ runner.os }}-go- - run: sudo apt-get update -y && sudo apt-get install -y expect - - run: git config --global url.https://$GH_ACCESS_TOKEN@github.com/.insteadOf https://github.com/ + - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" + - run: go env -w "github.com/bnb-chain/*" # used to debug workflow # - name: Setup tmate session # uses: mxschmitt/action-tmate@v3 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 248f187ad..6fc03759e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,7 +5,6 @@ on: # Publish `v1.2.3` tags as releases. tags: - v* - - t* jobs: build: From 7cca18438e590d25997cdf20028b9f7e5051074f Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 10:56:35 +0800 Subject: [PATCH 17/43] update release --- .github/workflows/release.yml | 42 +++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6fc03759e..6afc011f0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,10 +12,7 @@ jobs: strategy: matrix: go-version: [1.16.x] - os: [ubuntu-18.04, macos-11] - env: - GOPRIVATE: github.com/bnb-chain/* - GH_ACCESS_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }} + os: [ubuntu-18.04, macos-11, windows-2019] runs-on: ${{ matrix.os }} steps: - name: Checkout Code @@ -42,16 +39,21 @@ jobs: restore-keys: | ${{ runner.os }}-go- - - run: git config --global url.https://$GH_ACCESS_TOKEN@github.com/.insteadOf https://github.com/ + - run: go env -w GOPRIVATE="github.com/bnb-chain/*" + - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" # ============================== # Linux/Macos/Windows Build # ============================== +# used to debug workflow +# - name: Setup tmate session +# uses: mxschmitt/action-tmate@v3 + - name: Build Binary for ${{matrix.os}} run: make build - - run: mv build bnbchain-binaries - - run: zip -r bnbchain-binaries.zip bnbchain-binaries + - run: mv build bnb-chain-node-binary + - run: zip -r bnb-chain-node-binary.zip bnb-chain-node-binary # ============================== # Upload artifacts @@ -62,21 +64,21 @@ jobs: if: matrix.os == 'ubuntu-18.04' with: name: linux - path: ./bnbchain-binaries.zip + path: ./bnb-chain-node-binary.zip - name: Upload MacOS Build uses: actions/upload-artifact@v2 if: matrix.os == 'macos-11' with: name: macos - path: ./bnbchain-binaries.zip + path: ./bnb-chain-node-binary.zip - name: Upload Windows Build uses: actions/upload-artifact@v2 if: matrix.os == 'windows-2019' with: name: windows - path: ./bnbchain-binaries.zip + path: ./bnb-chain-node-binary.zip release: name: Release @@ -102,6 +104,12 @@ jobs: name: macos path: ./macos.zip + - name: Download Artifacts + uses: actions/download-artifact@v2 + with: + name: windows + path: ./windows.zip + - name: Create Release id: create_release uses: actions/create-release@latest @@ -123,7 +131,7 @@ jobs: with: upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps asset_path: ./linux.zip - asset_name: bnbchain-linux-${{ github.ref_name }}.zip + asset_name: bnb-chain-node-binary-linux-${{ github.ref_name }}.zip asset_content_type: application/octet-stream - name: Upload Release Asset - MacOS @@ -133,5 +141,15 @@ jobs: with: upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps asset_path: ./macos.zip - asset_name: bnbchain-macos-${{ github.ref_name }}.zip + asset_name: bnb-chain-node-binary-macos-${{ github.ref_name }}.zip + asset_content_type: application/octet-stream + + - name: Upload Release Asset - Windows + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps + asset_path: ./windows.zip + asset_name: bnb-chain-node-binary-windows-${{ github.ref_name }}.zip asset_content_type: application/octet-stream From 7fb3a699fa95efa29ecc62a6e975d307ab42e720 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 11:00:21 +0800 Subject: [PATCH 18/43] fix integration test --- .github/workflows/integration.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 6b7920ba2..3bc04d588 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -23,7 +23,7 @@ jobs: ${{ runner.os }}-go- - run: sudo apt-get update -y && sudo apt-get install -y expect - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" - - run: go env -w "github.com/bnb-chain/*" + - run: go env -w GOPRIVATE="github.com/bnb-chain/*" # used to debug workflow # - name: Setup tmate session # uses: mxschmitt/action-tmate@v3 From 9b2b1f87465d3f50a930b24f75f12fced6e88481 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 11:09:18 +0800 Subject: [PATCH 19/43] debug --- .github/workflows/integration.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 3bc04d588..4655f87f8 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -5,6 +5,8 @@ on: ["push", "pull_request", "workflow_dispatch"] jobs: integration-test: runs-on: ubuntu-latest + env: + GH_ACCESS_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }} steps: - uses: actions/checkout@v3 - name: Setup go @@ -25,7 +27,7 @@ jobs: - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" - run: go env -w GOPRIVATE="github.com/bnb-chain/*" # used to debug workflow -# - name: Setup tmate session -# uses: mxschmitt/action-tmate@v3 + - name: Setup tmate session + uses: mxschmitt/action-tmate@v3 - run: make integration_test - run: make test From 2648a48ba673b85851817758d4e4f58dab1a430e Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 11:15:56 +0800 Subject: [PATCH 20/43] remove debug --- .github/workflows/integration.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 4655f87f8..c4c84d86a 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -27,7 +27,7 @@ jobs: - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" - run: go env -w GOPRIVATE="github.com/bnb-chain/*" # used to debug workflow - - name: Setup tmate session - uses: mxschmitt/action-tmate@v3 +# - name: Setup tmate session +# uses: mxschmitt/action-tmate@v3 - run: make integration_test - run: make test From b6169eabfd7156d1fb88fcee1596ad12d487f9cd Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 11:26:04 +0800 Subject: [PATCH 21/43] clean up --- scripts/get_tools.sh | 45 ++------------------------------------------ 1 file changed, 2 insertions(+), 43 deletions(-) diff --git a/scripts/get_tools.sh b/scripts/get_tools.sh index 6a0de1404..48eac8b5c 100755 --- a/scripts/get_tools.sh +++ b/scripts/get_tools.sh @@ -1,47 +1,6 @@ #!/usr/bin/env bash -set -e +set -ex -# This file downloads all of the binary dependencies we have, and checks out a -# specific git hash. - -## check if GOPATH is set -#if [ -z ${GOPATH+x} ]; then -# echo "please set GOPATH (https://github.com/golang/go/wiki/SettingGOPATH)" -# exit 1 -#fi -# -#mkdir -p "$GOPATH/src/github.com" -#cd "$GOPATH/src/github.com" || exit 1 -# -#installFromGithub() { -# repo=$1 -# commit=$2 -# # optional -# subdir=$3 -# echo "--> Installing $repo ($commit)..." -# if [ ! -d "$repo" ]; then -# mkdir -p "$repo" -# git clone "https://github.com/$repo.git" "$repo" -# fi -# if [ ! -z ${subdir+x} ] && [ ! -d "$repo/$subdir" ]; then -# echo "ERROR: no such directory $repo/$subdir" -# exit 1 -# fi -# pushd "$repo" && \ -# git fetch origin && \ -# git checkout -q "$commit" && \ -# if [ ! -z ${subdir+x} ]; then cd "$subdir" || exit 1; fi && \ -# go install && \ -# if [ ! -z ${subdir+x} ]; then cd - || exit 1; fi && \ -# popd || exit 1 -# echo "--> Done" -# echo "" -#} - -######################## COMMON TOOLS ######################################## -## XXX: https://github.com/tendermint/tendermint/issues/3242 -#installFromGithub petermattis/goid b0b1615b78e5ee59739545bb38426383b2cda4c9 -#installFromGithub sasha-s/go-deadlock d68e2bc52ae3291765881b9056f2c1527f245f1e +go install golang.org/x/tools/cmd/goimports@latest go get github.com/petermattis/goid@b0b1615b78e5ee59739545bb38426383b2cda4c9 go get github.com/sasha-s/go-deadlock@d68e2bc52ae3291765881b9056f2c1527f245f1e -go install golang.org/x/tools/cmd/goimports@latest From aa35d7d489d17d3843769762b2463709ec1fe86b Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 11:39:05 +0800 Subject: [PATCH 22/43] adjust release strategy --- .github/workflows/release.yml | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6afc011f0..51dd992fa 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -52,8 +52,6 @@ jobs: - name: Build Binary for ${{matrix.os}} run: make build - - run: mv build bnb-chain-node-binary - - run: zip -r bnb-chain-node-binary.zip bnb-chain-node-binary # ============================== # Upload artifacts @@ -64,21 +62,21 @@ jobs: if: matrix.os == 'ubuntu-18.04' with: name: linux - path: ./bnb-chain-node-binary.zip + path: ./build - name: Upload MacOS Build uses: actions/upload-artifact@v2 if: matrix.os == 'macos-11' with: name: macos - path: ./bnb-chain-node-binary.zip + path: ./build - name: Upload Windows Build uses: actions/upload-artifact@v2 if: matrix.os == 'windows-2019' with: name: windows - path: ./bnb-chain-node-binary.zip + path: ./build release: name: Release @@ -96,19 +94,25 @@ jobs: uses: actions/download-artifact@v2 with: name: linux - path: ./linux.zip + path: ./linux - name: Download Artifacts uses: actions/download-artifact@v2 with: name: macos - path: ./macos.zip + path: ./macos - name: Download Artifacts uses: actions/download-artifact@v2 with: name: windows - path: ./windows.zip + path: ./windows + + - name: Zip Binaries + - run: | + zip -r linux.zip linux + zip -r macos.zip macos + zip -r windows.zip windows - name: Create Release id: create_release From 179b4dcf1785785a6cb746a7fc9fbebfeb4cd4b4 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 11:42:25 +0800 Subject: [PATCH 23/43] fix multiple cmds --- .github/workflows/release.yml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 51dd992fa..b9633943c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -108,11 +108,9 @@ jobs: name: windows path: ./windows - - name: Zip Binaries - - run: | - zip -r linux.zip linux - zip -r macos.zip macos - zip -r windows.zip windows + - run: zip -r linux.zip linux + - run: zip -r macos.zip macos + - run: zip -r windows.zip windows - name: Create Release id: create_release From e4527150cabd95d9a5246c0a7ad30e7c2429f007 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 13:34:04 +0800 Subject: [PATCH 24/43] fix paramhub --- app/{app_paramhub_test.go.bak => app_paramhub_test.go} | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) rename app/{app_paramhub_test.go.bak => app_paramhub_test.go} (96%) diff --git a/app/app_paramhub_test.go.bak b/app/app_paramhub_test.go similarity index 96% rename from app/app_paramhub_test.go.bak rename to app/app_paramhub_test.go index fe9d9ce70..001f3bf3c 100644 --- a/app/app_paramhub_test.go.bak +++ b/app/app_paramhub_test.go @@ -9,6 +9,8 @@ import ( "testing" "time" + "github.com/bnb-chain/node/common/upgrade" + "github.com/stretchr/testify/assert" "github.com/tendermint/go-amino" @@ -50,7 +52,7 @@ var ( logger = log.NewTMLogger(os.Stdout) genAccs, addrs, pubKeys, privKeys = mock.CreateGenAccounts(4, sdk.Coins{sdk.NewCoin("BNB", 500000e8), sdk.NewCoin("BTC-000", 200e8)}) - testScParams = `[{"type": "params/StakeParamSet","value": {"unbonding_time": "604800000000000","max_validators": 11,"bond_denom": "BNB","min_self_delegation": "5000000000000","min_delegation_change": "100000000","reward_distribution_batch_size":"200"}},{"type": "params/SlashParamSet","value": {"max_evidence_age": "259200000000000","signed_blocks_window": "0","min_signed_per_window": "0","double_sign_unbond_duration": "9223372036854775807","downtime_unbond_duration": "172800000000000","too_low_del_unbond_duration": "86400000000000","slash_fraction_double_sign": "0","slash_fraction_downtime": "0","double_sign_slash_amount": "1000000000000","downtime_slash_amount": "5000000000","submitter_reward": "100000000000","downtime_slash_fee": "1000000000"}},{"type": "params/OracleParamSet","value": {"ConsensusNeeded": "70000000"}},{"type": "params/IbcParamSet","value": {"relayer_fee": "1000000"}}]` + testScParams = `[{"type": "params/StakeParamSet","value": {"unbonding_time": "604800000000000","max_validators": 11,"bond_denom": "BNB","min_self_delegation": "5000000000000","min_delegation_change": "100000000","reward_distribution_batch_size":"1000"}},{"type": "params/SlashParamSet","value": {"max_evidence_age": "259200000000000","signed_blocks_window": "0","min_signed_per_window": "0","double_sign_unbond_duration": "9223372036854775807","downtime_unbond_duration": "172800000000000","too_low_del_unbond_duration": "86400000000000","slash_fraction_double_sign": "0","slash_fraction_downtime": "0","double_sign_slash_amount": "1000000000000","downtime_slash_amount": "5000000000","submitter_reward": "100000000000","downtime_slash_fee": "1000000000"}},{"type": "params/OracleParamSet","value": {"ConsensusNeeded": "70000000"}},{"type": "params/IbcParamSet","value": {"relayer_fee": "1000000"}}]` testClient *TestClient testApp *BinanceChain ) @@ -251,6 +253,7 @@ func TestSubmitCSCParamUpdatesFail(t *testing.T) { } func TestSCParamUpdatesSuccess(t *testing.T) { + upgrade.Mgr.AddUpgradeHeight(upgrade.BEP128, -1) valAddr, ctx, accounts := setupTest() sideValAddr := accounts[0].GetAddress().Bytes() tNow := time.Now() From 44538ac141d0832d6a03f5f6bc4ff76d6ec50402 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 13:35:18 +0800 Subject: [PATCH 25/43] get app_pub back --- app/{app_pub_test.go.bak => app_pub_test.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename app/{app_pub_test.go.bak => app_pub_test.go} (100%) diff --git a/app/app_pub_test.go.bak b/app/app_pub_test.go similarity index 100% rename from app/app_pub_test.go.bak rename to app/app_pub_test.go From ab08981017e17fd7810b70b54862b8c4556452aa Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 14:41:04 +0800 Subject: [PATCH 26/43] remove app_pub_test --- app/{app_pub_test.go => app_pub_test.go.bak} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename app/{app_pub_test.go => app_pub_test.go.bak} (100%) diff --git a/app/app_pub_test.go b/app/app_pub_test.go.bak similarity index 100% rename from app/app_pub_test.go rename to app/app_pub_test.go.bak From 821b28af0262437ebc29ccf1aa388b8c2bb8ee39 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 14:47:56 +0800 Subject: [PATCH 27/43] add lint --- .github/workflows/golangci-lint.yml | 48 +++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 .github/workflows/golangci-lint.yml diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml new file mode 100644 index 000000000..a47921b6a --- /dev/null +++ b/.github/workflows/golangci-lint.yml @@ -0,0 +1,48 @@ +name: golangci-lint + +on: + push: + tags: + - v* + branches: + - master + - main + pull_request: + workflow_dispatch: +permissions: + contents: read + # Optional: allow read access to pull request. Use with `only-new-issues` option. + # pull-requests: read +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - uses: actions/setup-go@v3 + with: + go-version: 1.16 + - uses: actions/checkout@v3 + - name: golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version + version: v1.29 + + # Optional: working directory, useful for monorepos + # working-directory: somedir + + # Optional: golangci-lint command line arguments. + # args: --issues-exit-code=0 + + # Optional: show only new issues if it's a pull request. The default value is `false`. + # only-new-issues: true + + # Optional: if set to true then the all caching functionality will be complete disabled, + # takes precedence over all other caching options. + # skip-cache: true + + # Optional: if set to true then the action don't cache or restore ~/go/pkg. + # skip-pkg-cache: true + + # Optional: if set to true then the action don't cache or restore ~/.cache/go-build. + # skip-build-cache: true \ No newline at end of file From c94706832f444440eb777bba5f5459197440c070 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 14:52:40 +0800 Subject: [PATCH 28/43] fix lint --- .github/workflows/golangci-lint.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index a47921b6a..73ffe9128 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -22,6 +22,8 @@ jobs: with: go-version: 1.16 - uses: actions/checkout@v3 + - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" + - run: go env -w GOPRIVATE="github.com/bnb-chain/*" - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: @@ -45,4 +47,4 @@ jobs: # skip-pkg-cache: true # Optional: if set to true then the action don't cache or restore ~/.cache/go-build. - # skip-build-cache: true \ No newline at end of file + # skip-build-cache: true From b33209576762ba34366b8982fd8077a1678ae268 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Fri, 22 Apr 2022 15:17:37 +0800 Subject: [PATCH 29/43] fix pub --- .github/workflows/golangci-lint.yml | 50 -------------------- app/{app_pub_test.go.bak => app_pub_test.go} | 0 app/pub/publisher.go | 2 +- 3 files changed, 1 insertion(+), 51 deletions(-) delete mode 100644 .github/workflows/golangci-lint.yml rename app/{app_pub_test.go.bak => app_pub_test.go} (100%) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml deleted file mode 100644 index 73ffe9128..000000000 --- a/.github/workflows/golangci-lint.yml +++ /dev/null @@ -1,50 +0,0 @@ -name: golangci-lint - -on: - push: - tags: - - v* - branches: - - master - - main - pull_request: - workflow_dispatch: -permissions: - contents: read - # Optional: allow read access to pull request. Use with `only-new-issues` option. - # pull-requests: read -jobs: - golangci: - name: lint - runs-on: ubuntu-latest - steps: - - uses: actions/setup-go@v3 - with: - go-version: 1.16 - - uses: actions/checkout@v3 - - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" - - run: go env -w GOPRIVATE="github.com/bnb-chain/*" - - name: golangci-lint - uses: golangci/golangci-lint-action@v3 - with: - # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version - version: v1.29 - - # Optional: working directory, useful for monorepos - # working-directory: somedir - - # Optional: golangci-lint command line arguments. - # args: --issues-exit-code=0 - - # Optional: show only new issues if it's a pull request. The default value is `false`. - # only-new-issues: true - - # Optional: if set to true then the all caching functionality will be complete disabled, - # takes precedence over all other caching options. - # skip-cache: true - - # Optional: if set to true then the action don't cache or restore ~/go/pkg. - # skip-pkg-cache: true - - # Optional: if set to true then the action don't cache or restore ~/.cache/go-build. - # skip-build-cache: true diff --git a/app/app_pub_test.go.bak b/app/app_pub_test.go similarity index 100% rename from app/app_pub_test.go.bak rename to app/app_pub_test.go diff --git a/app/pub/publisher.go b/app/pub/publisher.go index 65b9c048c..31666a574 100644 --- a/app/pub/publisher.go +++ b/app/pub/publisher.go @@ -48,7 +48,7 @@ func PublishEvent( ToPublishEventCh <-chan *sub.ToPublishEvent) { for toPublish := range ToPublishEventCh { eventData := toPublish.EventData - Logger.Debug("publisher queue status", "size", len(ToPublishCh)) + //Logger.Debug("publisher queue status", "size", len(ToPublishCh)) if cfg.PublishStaking { var msgNum int var validators []*Validator From 02b65666929f97c15a34b77d0ae767ae3b45dbb5 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Sun, 24 Apr 2022 10:15:06 +0800 Subject: [PATCH 30/43] add lint --- .github/workflows/golangci-lint.yml | 24 +++++++++ .golangci.yml | 57 ++++++++++++++++++++++ Makefile | 10 +++- cmd/dexperf/main.go | 11 +++-- go.mod | 2 - go.sum | 5 -- networks/tools/snapshot_viewer/snapshot.go | 12 +++-- plugins/dex/list/handler.go | 4 +- plugins/tokens/genesis.go | 5 +- 9 files changed, 111 insertions(+), 19 deletions(-) create mode 100644 .github/workflows/golangci-lint.yml create mode 100644 .golangci.yml diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml new file mode 100644 index 000000000..9d8a46a26 --- /dev/null +++ b/.github/workflows/golangci-lint.yml @@ -0,0 +1,24 @@ +name: golangci-lint + +on: + push: + tags: + - v* + branches: + - master + - main + pull_request: + workflow_dispatch: +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - uses: actions/setup-go@v3 + with: + go-version: 1.16 + - uses: actions/checkout@v3 + - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" + - run: go env -w GOPRIVATE="github.com/bnb-chain/*" + - name: golangci-lint + run: make lint diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..16acc680e --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,57 @@ +# Options for analysis running. +run: + # The default concurrency value is the number of available CPU. + # concurrency: 4 + # Timeout for analysis, e.g. 30s, 5m. + # Default: 1m + # timeout: 5m + # Exit code when at least one issue was found. + # Default: 1 + # issues-exit-code: 2 + # Include test files or not. + # Default: true + tests: false + # List of build tags, all linters use it. + # Default: []. +# build-tags: +# - mytag + # Which dirs to skip: issues from them won't be reported. + # Can use regexp here: `generated.*`, regexp is applied on full path. + # Default value is empty list, + # but default dirs are skipped independently of this option's value (see skip-dirs-use-default). + # "/" will be replaced by current OS file path separator to properly work on Windows. +# skip-dirs: +# - src/external_libs +# - autogenerated_by_my_lib + # Enables skipping of directories: + # - vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ + # Default: true +# skip-dirs-use-default: false + # Which files to skip: they will be analyzed, but issues from them won't be reported. + # Default value is empty list, + # but there is no need to include all autogenerated files, + # we confidently recognize autogenerated files. + # If it's not please let us know. + # "/" will be replaced by current OS file path separator to properly work on Windows. +# skip-files: +# - ".*\\.my\\.go$" +# - lib/bad.go + # If set we pass it to "go list -mod={option}". From "go help modules": + # If invoked with -mod=readonly, the go command is disallowed from the implicit + # automatic updating of go.mod described above. Instead, it fails when any changes + # to go.mod are needed. This setting is most useful to check that go.mod does + # not need updates, such as in a continuous integration and testing system. + # If invoked with -mod=vendor, the go command assumes that the vendor + # directory holds the correct copies of dependencies and ignores + # the dependency descriptions in go.mod. + # + # Allowed values: readonly|vendor|mod + # By default, it isn't set. +# modules-download-mode: readonly + # Allow multiple parallel golangci-lint instances running. + # If false (default) - golangci-lint acquires file lock on start. +# allow-parallel-runners: false + # Define the Go version limit. + # Mainly related to generics support in go1.18. + # Default: use Go version from the go.mod file, fallback on the env var `GOVERSION`, fallback on 1.17 +# go: '1.16' \ No newline at end of file diff --git a/Makefile b/Makefile index 9ccd16ead..0220b9c71 100644 --- a/Makefile +++ b/Makefile @@ -193,7 +193,14 @@ integration_test: build ######################################## ### Pre Commit -pre_commit: build test format +pre_commit: build test format lint + +install_lint: + which golangci-lint || curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.45.2 + golangci-lint --version + +lint: install_lint + golangci-lint run ######################################## ### Local validator nodes using docker and docker-compose @@ -227,3 +234,4 @@ localnet-stop: # unless there is a reason not to. # https://www.gnu.org/software/make/manual/html_node/Phony-Targets.html .PHONY: build install test test_unit build-linux build-docker-node localnet-start localnet-stop +.PHONY: lint install_lint diff --git a/cmd/dexperf/main.go b/cmd/dexperf/main.go index 370589546..2ad0f03b5 100644 --- a/cmd/dexperf/main.go +++ b/cmd/dexperf/main.go @@ -178,17 +178,17 @@ func main() { if tokens == nil { path := filepath.Join(*csvPath, "tokens.csv") file, err := os.Open(path) - defer file.Close() if err != nil { panic(err) } + defer file.Close() s := bufio.NewScanner(file) for s.Scan() { tokens = append(tokens, s.Text()) } fmt.Println("issued tokens:", tokens) } - initializeAccounts(tokens, *initiateAccount) + tokens = initializeAccounts(tokens, *initiateAccount) if *runCreate == true { createFolder(*createPath) @@ -351,12 +351,12 @@ func generateTokens(sIndex int, eIndex int, flag bool) []string { return tokens } -func initializeAccounts(tokens []string, flag bool) { +func initializeAccounts(tokens []string, flag bool) []string { tokens = append(tokens, "BNB") if flag == true { type Transfer struct { - To string `json:to` - Amount string `json:amount` + To string `json:"to"` + Amount string `json:"amount"` } b := 0 transfers := make([]Transfer, 2000) @@ -395,6 +395,7 @@ func initializeAccounts(tokens []string, flag bool) { } } tokens = tokens[:len(tokens)-1] + return tokens } func createFolder(path string) { diff --git a/go.mod b/go.mod index baf6839c9..a7014087b 100644 --- a/go.mod +++ b/go.mod @@ -14,10 +14,8 @@ require ( github.com/linkedin/goavro v0.0.0-20180427201934-fa8f6a30176c github.com/mitchellh/go-homedir v1.1.0 github.com/natefinch/lumberjack v2.0.0+incompatible - github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect github.com/pkg/errors v0.8.1 github.com/prometheus/client_golang v1.1.0 - github.com/sasha-s/go-deadlock v0.2.1-0.20180822072021-d68e2bc52ae3 // indirect github.com/spf13/cobra v0.0.5 github.com/spf13/viper v1.4.0 github.com/stretchr/testify v1.4.0 diff --git a/go.sum b/go.sum index f490d587a..459003dce 100644 --- a/go.sum +++ b/go.sum @@ -403,8 +403,6 @@ github.com/otiai10/primes v0.0.0-20180210170552-f6d2a1ba97c4/go.mod h1:UmSP7QeU3 github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.4.0 h1:u3Z1r+oOXJIkxqw34zVhyPgjBsm6X2wn21NWs/HfSeg= github.com/pelletier/go-toml v1.4.0/go.mod h1:PN7xzY2wHTK0K9p34ErDQMlFxa51Fk0OUruD3k1mMwo= -github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 h1:q2e307iGHPdTGp0hoxKjt1H5pDo6utceo3dQVK3I5XQ= -github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= github.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2/go.mod h1:iIss55rKnNBTvrwdmkUpLnDpZoAHvWaiq5+iMmen4AE= github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= @@ -442,8 +440,6 @@ github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6So github.com/rs/cors v1.6.0 h1:G9tHG9lebljV9mfp9SNPDL36nCDxmo3zTlAf1YgvzmI= github.com/rs/cors v1.6.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= -github.com/sasha-s/go-deadlock v0.2.1-0.20180822072021-d68e2bc52ae3 h1:PFrDl/KPigLkWkRl/AqIztEvC/iSnwKmTCy9qbqgevw= -github.com/sasha-s/go-deadlock v0.2.1-0.20180822072021-d68e2bc52ae3/go.mod h1:StQn567HiB1fF2yJ44N9au7wOhrPS3iZqiDbRupzT10= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/smola/gocompat v0.2.0/go.mod h1:1B0MlxbmoZNo3h8guHp8HztB3BSYR5itql9qtVc0ypY= github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa/go.mod h1:oJyF+mSPHbB5mVY2iO9KV3pTt/QbIkGaO8gQ2WrDbP4= @@ -576,7 +572,6 @@ golang.org/x/tools v0.0.0-20181130052023-1c3d964395ce/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135 h1:5Beo0mZN8dRzgrMMkDp0jc8YXQKx9DiJ2k1dkvGsn5A= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898 h1:/atklqdjdhuosWIl6AIbOeHJjicWYPqR9bpxqxYG2pA= diff --git a/networks/tools/snapshot_viewer/snapshot.go b/networks/tools/snapshot_viewer/snapshot.go index 68a14af29..8ba859aff 100644 --- a/networks/tools/snapshot_viewer/snapshot.go +++ b/networks/tools/snapshot_viewer/snapshot.go @@ -56,7 +56,7 @@ func prepareCms(root string, appDB *db.GoLevelDB) sdk.CommitMultiStore { } err := cms.LoadLatestVersion() if err != nil { - fmt.Printf(err.Error()) + fmt.Print(err.Error()) panic(err) } return cms @@ -144,9 +144,15 @@ func analyseSnapshot(height int64, home string) { func uncompress(bz []byte) []byte { b := bytes.NewReader(bz) var out bytes.Buffer - r, _ := zlib.NewReader(b) + r, err := zlib.NewReader(b) + if err != nil { + panic(err) + } defer r.Close() - io.Copy(&out, r) + _, err = io.Copy(&out, r) + if err != nil { + panic(err) + } return out.Bytes() } diff --git a/plugins/dex/list/handler.go b/plugins/dex/list/handler.go index 2325dc8d4..f88d6b85a 100644 --- a/plugins/dex/list/handler.go +++ b/plugins/dex/list/handler.go @@ -58,12 +58,12 @@ func checkListProposal(ctx sdk.Context, govKeeper gov.Keeper, msg types.ListMsg) return fmt.Errorf("list time expired, expire_time=%s", listParams.ExpireTime.String()) } - if strings.ToUpper(msg.BaseAssetSymbol) != strings.ToUpper(listParams.BaseAssetSymbol) { + if !strings.EqualFold(msg.BaseAssetSymbol, listParams.BaseAssetSymbol) { return fmt.Errorf("base asset symbol(%s) is not identical to symbol in proposal(%s)", msg.BaseAssetSymbol, listParams.BaseAssetSymbol) } - if strings.ToUpper(msg.QuoteAssetSymbol) != strings.ToUpper(listParams.QuoteAssetSymbol) { + if !strings.EqualFold(msg.QuoteAssetSymbol, listParams.QuoteAssetSymbol) { return fmt.Errorf("quote asset symbol(%s) is not identical to symbol in proposal(%s)", msg.QuoteAssetSymbol, listParams.QuoteAssetSymbol) } diff --git a/plugins/tokens/genesis.go b/plugins/tokens/genesis.go index c158dda41..e1e6a7e02 100644 --- a/plugins/tokens/genesis.go +++ b/plugins/tokens/genesis.go @@ -74,5 +74,8 @@ func transferNativeTokensToValidators(ctx sdk.Context, coinKeeper bank.Keeper, inputs := []bank.Input{ bank.NewInput(nativeTokenOwner, sdk.Coins{sdk.NewCoin(types.NativeTokenSymbol, amtForEach*int64(numValidators))}), } - coinKeeper.InputOutputCoins(ctx, inputs, outputs) + _, sdkErr := coinKeeper.InputOutputCoins(ctx, inputs, outputs) + if sdkErr != nil { + panic(sdkErr) + } } From ea571b7cc25e0ecee7ace79e75ef88d9d61995dd Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Sun, 24 Apr 2022 10:19:16 +0800 Subject: [PATCH 31/43] fix lint --- Makefile | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/Makefile b/Makefile index 0220b9c71..bb2a33c76 100644 --- a/Makefile +++ b/Makefile @@ -144,9 +144,13 @@ format: ######################################## ### Lint -lint: +install_lint: + which golangci-lint || curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.45.2 + golangci-lint --version + +lint: install_lint @echo "-->Lint" - golint $(PACKAGES) + golangci-lint run ######################################## ### Testing @@ -195,13 +199,6 @@ integration_test: build ### Pre Commit pre_commit: build test format lint -install_lint: - which golangci-lint || curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.45.2 - golangci-lint --version - -lint: install_lint - golangci-lint run - ######################################## ### Local validator nodes using docker and docker-compose build-docker-node: From 9f2b3959397f7163ce2e1c45eb13174a25d182a1 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Sun, 24 Apr 2022 10:22:27 +0800 Subject: [PATCH 32/43] fix ci --- .github/workflows/golangci-lint.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 9d8a46a26..168e6e6d0 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -20,5 +20,6 @@ jobs: - uses: actions/checkout@v3 - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" - run: go env -w GOPRIVATE="github.com/bnb-chain/*" + - run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.45.2 - name: golangci-lint run: make lint From f87477b8ef62f0554f142bc8616ac1e2d66b1d47 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Sun, 24 Apr 2022 10:28:57 +0800 Subject: [PATCH 33/43] add timeout --- .github/workflows/integration.yml | 3 ++- .golangci.yml | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index c4c84d86a..c47648963 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -1,6 +1,7 @@ name: integration-ci -on: ["push", "pull_request", "workflow_dispatch"] +on: ["workflow_dispatch"] +#on: ["push", "pull_request", "workflow_dispatch"] jobs: integration-test: diff --git a/.golangci.yml b/.golangci.yml index 16acc680e..0cc0daa88 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -4,7 +4,7 @@ run: # concurrency: 4 # Timeout for analysis, e.g. 30s, 5m. # Default: 1m - # timeout: 5m + timeout: 5m # Exit code when at least one issue was found. # Default: 1 # issues-exit-code: 2 From 98ea4986da52edcbc486940cf3101385634b7128 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Sun, 24 Apr 2022 10:29:44 +0800 Subject: [PATCH 34/43] add cache --- .github/workflows/golangci-lint.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 168e6e6d0..a1eb5f474 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -18,6 +18,14 @@ jobs: with: go-version: 1.16 - uses: actions/checkout@v3 + - uses: actions/cache@v2 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" - run: go env -w GOPRIVATE="github.com/bnb-chain/*" - run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.45.2 From 0ce886e3bf5740b86ae665c8d48220f8990083d2 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Sun, 24 Apr 2022 15:18:18 +0800 Subject: [PATCH 35/43] fix lint --- .github/workflows/golangci-lint.yml | 1 + app/app.go | 7 ++-- app/fee_distribution.go | 8 ++-- app/helpers.go | 4 +- app/pub/helpers.go | 18 ++++---- app/pub/msgs.go | 42 +++++++++---------- app/pub/msgs_cross.go | 4 +- app/pub/msgs_mirror.go | 2 +- app/pub/msgs_staking.go | 20 ++++----- app/pub/publisher.go | 36 ++++++++-------- app/pub/sub/cross.go | 8 ++-- app/pub/sub/mirror.go | 4 +- app/pub/sub/slash.go | 4 +- app/sentryapp.go | 10 ++--- cmd/bnbchaind/init/init.go | 5 ++- cmd/bnbchaind/init/snapshot.go | 15 ++++--- cmd/bnbchaind/init/testnet.go | 7 +++- cmd/bnbchaind/main.go | 2 +- cmd/bnbcli/main.go | 2 +- cmd/bnbsentry/main.go | 4 +- cmd/dexperf/main.go | 1 + cmd/pressuremaker/main.go | 5 ++- cmd/pressuremaker/utils/utils.go | 1 + common/log/async_file_writer.go | 2 +- common/log/logger.go | 5 ++- common/testutils/testutils.go | 11 +++-- common/types/token.go | 8 +--- common/utils/ring.go | 2 +- .../tools/account_viewer/account_viewer.go | 13 ++++-- networks/tools/compare/compare.go | 11 ++--- networks/tools/snapshot_viewer/snapshot.go | 4 +- networks/tools/state_recover/state_recover.go | 10 +++-- plugins/api/handlers.go | 1 + plugins/api/handlers/account.go | 7 ++-- plugins/api/handlers/simulate.go | 5 +-- plugins/api/handlers/stake.go | 10 ++--- plugins/api/handlers/version.go | 6 +-- plugins/bridge/cross_app.go | 4 +- plugins/bridge/types/msgs.go | 2 +- plugins/bridge/types/serialize.go | 2 +- plugins/dex/abci.go | 2 +- plugins/dex/client/rest/getdepth.go | 3 +- plugins/dex/client/rest/getpairs.go | 7 ++-- plugins/dex/client/rest/openorders.go | 3 +- plugins/dex/client/rest/putorder.go | 5 +-- plugins/dex/matcheng/engine.go | 10 ++++- plugins/dex/matcheng/match.go | 5 +-- plugins/dex/matcheng/orderbook.go | 1 + plugins/dex/matcheng/types.go | 4 -- plugins/dex/order/fee.go | 4 -- plugins/dex/order/handler.go | 4 +- plugins/dex/order/keeper.go | 1 + plugins/dex/order/keeper_match.go | 3 +- plugins/dex/order/keeper_recovery.go | 32 ++++++++++---- plugins/dex/order/mini_keeper.go | 4 -- plugins/dex/order/msg.go | 3 +- plugins/dex/order/order_keeper.go | 22 ++++------ plugins/dex/order/wal.go | 11 +---- plugins/dex/plugin.go | 1 - plugins/dex/store/codec.go | 8 ++-- plugins/dex/store/mapper.go | 2 +- plugins/tokens/client/cli/atomic_swap.go | 7 +++- plugins/tokens/client/cli/issue.go | 4 +- plugins/tokens/client/cli/issue_mini.go | 2 +- plugins/tokens/client/cli/issue_tiny.go | 2 +- plugins/tokens/client/cli/multi_send.go | 2 +- plugins/tokens/client/rest/getbalance.go | 5 +-- plugins/tokens/client/rest/getbalances.go | 5 +-- plugins/tokens/client/rest/getswap.go | 5 +-- .../tokens/client/rest/getswapsbycreator.go | 5 +-- .../tokens/client/rest/getswapsbyrecipient.go | 5 +-- plugins/tokens/client/rest/gettimelock.go | 5 +-- plugins/tokens/client/rest/gettimelocks.go | 5 +-- plugins/tokens/client/rest/gettoken.go | 5 +-- plugins/tokens/client/rest/gettokens.go | 5 +-- plugins/tokens/client/rest/helpers.go | 5 +-- plugins/tokens/freeze/handler.go | 4 +- plugins/tokens/issue/handler.go | 2 +- plugins/tokens/issue/msg.go | 2 +- plugins/tokens/seturi/handler.go | 4 +- plugins/tokens/swap/handler.go | 2 +- plugins/tokens/timelock/msgs.go | 2 +- 82 files changed, 261 insertions(+), 270 deletions(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index a1eb5f474..16ea5fb0d 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -21,6 +21,7 @@ jobs: - uses: actions/cache@v2 with: path: | + ~/go/bin ~/go/pkg/mod ~/.cache/go-build key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} diff --git a/app/app.go b/app/app.go index f2a8c76b3..e73862a45 100644 --- a/app/app.go +++ b/app/app.go @@ -135,7 +135,7 @@ func NewBinanceChain(logger log.Logger, db dbm.DB, traceStore io.Writer, baseApp // create the applicationsimulate object var app = &BinanceChain{ - BaseApp: baseapp.NewBaseApp(appName /*, cdc*/, logger, db, decoders, sdk.CollectConfig{ServerContext.PublishAccountBalance, ServerContext.PublishTransfer || ServerContext.PublishBlock}, baseAppOptions...), + BaseApp: baseapp.NewBaseApp(appName /*, cdc*/, logger, db, decoders, sdk.CollectConfig{CollectAccountBalance: ServerContext.PublishAccountBalance, CollectTxs: ServerContext.PublishTransfer || ServerContext.PublishBlock}, baseAppOptions...), Codec: cdc, queryHandlers: make(map[string]types.AbciQueryHandler), baseConfig: ServerContext.BaseConfig, @@ -839,8 +839,7 @@ func (app *BinanceChain) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) a if app.publicationConfig.ShouldPublishAny() && pub.IsLive { - var stakeUpdates pub.StakeUpdates - stakeUpdates = pub.CollectStakeUpdatesForPublish(completedUbd) + stakeUpdates := pub.CollectStakeUpdatesForPublish(completedUbd) if height >= app.publicationConfig.FromHeightInclusive { app.publish(tradesToPublish, &proposals, &sideProposals, &stakeUpdates, blockFee, ctx, height, blockTime.UnixNano()) @@ -961,7 +960,7 @@ func (app *BinanceChain) AccountHandler(chainApp types.ChainApp, req abci.Reques // let api server return 204 No Content res = abci.ResponseQuery{ Code: uint32(sdk.ABCICodeOK), - Value: make([]byte, 0, 0), + Value: make([]byte, 0), } } } else { diff --git a/app/fee_distribution.go b/app/fee_distribution.go index 66cc1b800..b5c59bae5 100644 --- a/app/fee_distribution.go +++ b/app/fee_distribution.go @@ -69,7 +69,7 @@ func distributeFee(ctx sdk.Context, am auth.AccountKeeper, valAddrCache *ValAddr if fee.Type == sdk.FeeForProposer { // The proposer's account must be initialized before it becomes a proposer. proposerAcc := am.GetAccount(ctx, proposerAccAddr) - proposerAcc.SetCoins(proposerAcc.GetCoins().Plus(fee.Tokens)) + _ = proposerAcc.SetCoins(proposerAcc.GetCoins().Plus(fee.Tokens)) am.SetAccount(ctx, proposerAcc) } else if fee.Type == sdk.FeeForAll { log.Info("Distributing the fees to all the validators", @@ -91,7 +91,7 @@ func distributeFee(ctx sdk.Context, am auth.AccountKeeper, valAddrCache *ValAddr if avgTokens.IsZero() { proposerAcc := am.GetAccount(ctx, proposerAccAddr) - proposerAcc.SetCoins(proposerAcc.GetCoins().Plus(fee.Tokens)) + _ = proposerAcc.SetCoins(proposerAcc.GetCoins().Plus(fee.Tokens)) am.SetAccount(ctx, proposerAcc) } else { for _, voteInfo := range voteInfos { @@ -100,12 +100,12 @@ func distributeFee(ctx sdk.Context, am auth.AccountKeeper, valAddrCache *ValAddr validatorAcc := am.GetAccount(ctx, accAddr) if bytes.Equal(proposerValAddr, validator.Address) { if !roundingTokens.IsZero() { - validatorAcc.SetCoins(validatorAcc.GetCoins().Plus(roundingTokens)) + _ = validatorAcc.SetCoins(validatorAcc.GetCoins().Plus(roundingTokens)) } } else if publishBlockFee { validators = append(validators, string(accAddr)) } - validatorAcc.SetCoins(validatorAcc.GetCoins().Plus(avgTokens)) + _ = validatorAcc.SetCoins(validatorAcc.GetCoins().Plus(avgTokens)) am.SetAccount(ctx, validatorAcc) } } diff --git a/app/helpers.go b/app/helpers.go index 69984f408..b707cf3dd 100644 --- a/app/helpers.go +++ b/app/helpers.go @@ -144,12 +144,12 @@ func (app *BinanceChain) processErrAbciResponseForPub(txBytes []byte) { case order.NewOrderMsg: app.Logger.Info("failed to process NewOrderMsg", "oid", msg.Id) // The error on deliver should be rare and only impact witness publisher's performance - app.DexKeeper.UpdateOrderChangeSync(order.OrderChange{msg.Id, order.FailedBlocking, "", msg}, msg.Symbol) + app.DexKeeper.UpdateOrderChangeSync(order.OrderChange{Id: msg.Id, Tpe: order.FailedBlocking, MsgForFailedTx: msg}, msg.Symbol) case order.CancelOrderMsg: app.Logger.Info("failed to process CancelOrderMsg", "oid", msg.RefId) // The error on deliver should be rare and only impact witness publisher's performance // OrderInfo must has been in keeper.orderInfosForPub - app.DexKeeper.UpdateOrderChangeSync(order.OrderChange{msg.RefId, order.FailedBlocking, "", msg}, msg.Symbol) + app.DexKeeper.UpdateOrderChangeSync(order.OrderChange{Id: msg.RefId, Tpe: order.FailedBlocking, MsgForFailedTx: msg}, msg.Symbol) default: // deliberately do nothing for message other than NewOrderMsg // in future, we may publish fail status of send msg diff --git a/app/pub/helpers.go b/app/pub/helpers.go index 722114f4e..eac4679c8 100644 --- a/app/pub/helpers.go +++ b/app/pub/helpers.go @@ -55,7 +55,7 @@ func GetTradeAndOrdersRelatedAccounts(tradesToPublish []*Trade, orderChanges ord func GetBlockPublished(pool *sdk.Pool, header abci.Header, blockHash []byte) *Block { txs := pool.GetTxs() - transactionsToPublish := make([]Transaction, 0, 0) + transactionsToPublish := make([]Transaction, 0) timeStamp := header.GetTime().Format(time.RFC3339Nano) txs.Range(func(key, value interface{}) bool { txhash := key.(string) @@ -181,7 +181,7 @@ func GetBlockPublished(pool *sdk.Pool, header abci.Header, blockHash []byte) *Bl } func GetTransferPublished(pool *sdk.Pool, height, blockTime int64) *Transfers { - transferToPublish := make([]Transfer, 0, 0) + transferToPublish := make([]Transfer, 0) txs := pool.GetTxs() txs.Range(func(key, value interface{}) bool { txhash := key.(string) @@ -281,9 +281,9 @@ func MatchAndAllocateAllForPublish(dexKeeper *orderPkg.DexKeeper, ctx sdk.Contex if tran.IsExpire() { if tran.IsExpiredWithFee() { // we only got expire of Ioc here, gte orders expire is handled in breathe block - iocExpireFeeHolderCh <- orderPkg.ExpireHolder{tran.Oid, orderPkg.IocNoFill, tran.Fee.String(), tran.Symbol} + iocExpireFeeHolderCh <- orderPkg.ExpireHolder{OrderId: tran.Oid, Reason: orderPkg.IocNoFill, Fee: tran.Fee.String(), Symbol: tran.Symbol} } else { - iocExpireFeeHolderCh <- orderPkg.ExpireHolder{tran.Oid, orderPkg.IocExpire, tran.Fee.String(), tran.Symbol} + iocExpireFeeHolderCh <- orderPkg.ExpireHolder{OrderId: tran.Oid, Reason: orderPkg.IocExpire, Fee: tran.Fee.String(), Symbol: tran.Symbol} } } } @@ -343,13 +343,12 @@ func ExpireOrdersForPublish( go updateExpireFeeForPublish(dexKeeper, &wg, expireHolderCh) var collectorForExpires = func(tran orderPkg.Transfer) { if tran.IsExpire() { - expireHolderCh <- orderPkg.ExpireHolder{tran.Oid, orderPkg.Expired, tran.Fee.String(), tran.Symbol} + expireHolderCh <- orderPkg.ExpireHolder{OrderId: tran.Oid, Reason: orderPkg.Expired, Fee: tran.Fee.String(), Symbol: tran.Symbol} } } dexKeeper.ExpireOrders(ctx, blockTime, collectorForExpires) close(expireHolderCh) wg.Wait() - return } func DelistTradingPairForPublish(ctx sdk.Context, dexKeeper *orderPkg.DexKeeper, symbol string) { @@ -359,13 +358,12 @@ func DelistTradingPairForPublish(ctx sdk.Context, dexKeeper *orderPkg.DexKeeper, go updateExpireFeeForPublish(dexKeeper, &wg, expireHolderCh) var collectorForExpires = func(tran orderPkg.Transfer) { if tran.IsExpire() { - expireHolderCh <- orderPkg.ExpireHolder{tran.Oid, orderPkg.Expired, tran.Fee.String(), tran.Symbol} + expireHolderCh <- orderPkg.ExpireHolder{OrderId: tran.Oid, Reason: orderPkg.Expired, Fee: tran.Fee.String(), Symbol: tran.Symbol} } } dexKeeper.DelistTradingPair(ctx, symbol, collectorForExpires) close(expireHolderCh) wg.Wait() - return } func CollectProposalsForPublish(passed, failed []gov.SimpleProposal) (Proposals, SideProposals) { @@ -405,7 +403,7 @@ func updateExpireFeeForPublish( defer wg.Done() for expHolder := range expHolderCh { Logger.Debug("transfer collector for order", "orderId", expHolder.OrderId) - change := orderPkg.OrderChange{expHolder.OrderId, expHolder.Reason, expHolder.Fee, nil} + change := orderPkg.OrderChange{Id: expHolder.OrderId, Tpe: expHolder.Reason, SingleFee: expHolder.Fee} dexKeeper.UpdateOrderChangeSync(change, expHolder.Symbol) } } @@ -428,7 +426,7 @@ func filterChangedOrderBooksByOrders( } allSymbols[symbol] = struct{}{} if _, ok := res[symbol]; !ok { - res[symbol] = orderPkg.ChangedPriceLevelsPerSymbol{make(map[int64]int64), make(map[int64]int64)} + res[symbol] = orderPkg.ChangedPriceLevelsPerSymbol{Buys: make(map[int64]int64), Sells: make(map[int64]int64)} buyQtyDiff[symbol] = make(map[int64]int64) sellQtyDiff[symbol] = make(map[int64]int64) } diff --git a/app/pub/msgs.go b/app/pub/msgs.go index 80f408e9f..6dcdb031f 100644 --- a/app/pub/msgs.go +++ b/app/pub/msgs.go @@ -191,7 +191,7 @@ func (msg *trades) String() string { func (msg *trades) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["numOfMsgs"] = msg.NumOfMsgs - ts := make([]map[string]interface{}, len(msg.Trades), len(msg.Trades)) + ts := make([]map[string]interface{}, len(msg.Trades)) for idx, trade := range msg.Trades { ts[idx] = trade.toNativeMap() } @@ -266,7 +266,7 @@ func (msg *Orders) String() string { func (msg *Orders) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["numOfMsgs"] = msg.NumOfMsgs - os := make([]map[string]interface{}, len(msg.Orders), len(msg.Orders)) + os := make([]map[string]interface{}, len(msg.Orders)) for idx, o := range msg.Orders { os[idx] = o.toNativeMap() } @@ -372,7 +372,7 @@ func (msg *Proposals) String() string { func (msg *Proposals) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["numOfMsgs"] = msg.NumOfMsgs - ps := make([]map[string]interface{}, len(msg.Proposals), len(msg.Proposals)) + ps := make([]map[string]interface{}, len(msg.Proposals)) for idx, p := range msg.Proposals { ps[idx] = p.toNativeMap() } @@ -396,7 +396,7 @@ func (msg *SideProposals) ToNativeMap() map[string]interface{} { native["numOfMsgs"] = msg.NumOfMsgs native["height"] = msg.Height native["timestamp"] = msg.Timestamp - ps := make([]map[string]interface{}, len(msg.Proposals), len(msg.Proposals)) + ps := make([]map[string]interface{}, len(msg.Proposals)) for idx, p := range msg.Proposals { ps[idx] = p.toNativeMap() } @@ -468,7 +468,7 @@ func (msg *StakeUpdates) String() string { func (msg *StakeUpdates) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["numOfMsgs"] = msg.NumOfMsgs - ps := make([]map[string]interface{}, len(msg.CompletedUnbondingDelegations), len(msg.CompletedUnbondingDelegations)) + ps := make([]map[string]interface{}, len(msg.CompletedUnbondingDelegations)) for idx, p := range msg.CompletedUnbondingDelegations { ps[idx] = p.toNativeMap() } @@ -505,12 +505,12 @@ func (msg *OrderBookDelta) String() string { func (msg *OrderBookDelta) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["symbol"] = msg.Symbol - bs := make([]map[string]interface{}, len(msg.Buys), len(msg.Buys)) + bs := make([]map[string]interface{}, len(msg.Buys)) for idx, buy := range msg.Buys { bs[idx] = buy.ToNativeMap() } native["buys"] = bs - ss := make([]map[string]interface{}, len(msg.Sells), len(msg.Sells)) + ss := make([]map[string]interface{}, len(msg.Sells)) for idx, sell := range msg.Sells { ss[idx] = sell.ToNativeMap() } @@ -536,7 +536,7 @@ func (msg *Books) ToNativeMap() map[string]interface{} { native["timestamp"] = msg.Timestamp native["numOfMsgs"] = msg.NumOfMsgs if msg.NumOfMsgs > 0 { - bs := make([]map[string]interface{}, len(msg.Books), len(msg.Books)) + bs := make([]map[string]interface{}, len(msg.Books)) for idx, book := range msg.Books { bs[idx] = book.ToNativeMap() } @@ -591,7 +591,7 @@ func (msg *Account) String() string { func (msg *Account) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["owner"] = sdk.AccAddress(msg.Owner).String() - bs := make([]map[string]interface{}, len(msg.Balances), len(msg.Balances)) + bs := make([]map[string]interface{}, len(msg.Balances)) for idx, b := range msg.Balances { bs[idx] = b.ToNativeMap() } @@ -616,7 +616,7 @@ func (msg *Accounts) ToNativeMap() map[string]interface{} { native["height"] = msg.Height native["numOfMsgs"] = msg.NumOfMsgs if msg.NumOfMsgs > 0 { - as := make([]map[string]interface{}, len(msg.Accounts), len(msg.Accounts)) + as := make([]map[string]interface{}, len(msg.Accounts)) for idx, a := range msg.Accounts { as[idx] = a.ToNativeMap() } @@ -650,7 +650,7 @@ type BlockFee struct { } func (msg BlockFee) MarshalJSON() ([]byte, error) { - bech32Strs := make([]string, len(msg.Validators), len(msg.Validators)) + bech32Strs := make([]string, len(msg.Validators)) for id, val := range msg.Validators { bech32Strs[id] = sdk.AccAddress(val).String() } @@ -672,7 +672,7 @@ func (msg BlockFee) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["height"] = msg.Height native["fee"] = msg.Fee - validators := make([]string, len(msg.Validators), len(msg.Validators)) + validators := make([]string, len(msg.Validators)) for idx, addr := range msg.Validators { validators[idx] = sdk.AccAddress(addr).String() } @@ -708,7 +708,7 @@ func (msg Receiver) String() string { func (msg Receiver) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["addr"] = msg.Addr - coins := make([]map[string]interface{}, len(msg.Coins), len(msg.Coins)) + coins := make([]map[string]interface{}, len(msg.Coins)) for idx, c := range msg.Coins { coins[idx] = c.ToNativeMap() } @@ -732,7 +732,7 @@ func (msg Transfer) ToNativeMap() map[string]interface{} { native["txhash"] = msg.TxHash native["memo"] = msg.Memo native["from"] = msg.From - to := make([]map[string]interface{}, len(msg.To), len(msg.To)) + to := make([]map[string]interface{}, len(msg.To)) for idx, t := range msg.To { to[idx] = t.ToNativeMap() } @@ -755,7 +755,7 @@ func (msg Transfers) String() string { func (msg Transfers) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["height"] = msg.Height - transfers := make([]map[string]interface{}, len(msg.Transfers), len(msg.Transfers)) + transfers := make([]map[string]interface{}, len(msg.Transfers)) for idx, t := range msg.Transfers { transfers[idx] = t.ToNativeMap() } @@ -885,7 +885,7 @@ type Input struct { func (msg Input) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["address"] = msg.Address - coins := make([]map[string]interface{}, len(msg.Coins), len(msg.Coins)) + coins := make([]map[string]interface{}, len(msg.Coins)) for idx, c := range msg.Coins { coins[idx] = c.ToNativeMap() } @@ -905,7 +905,7 @@ type Output struct { func (msg Output) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["address"] = msg.Address - coins := make([]map[string]interface{}, len(msg.Coins), len(msg.Coins)) + coins := make([]map[string]interface{}, len(msg.Coins)) for idx, c := range msg.Coins { coins[idx] = c.ToNativeMap() } @@ -959,7 +959,7 @@ func (msg *DistributionMsg) ToNativeMap() map[string]interface{} { distributions := make(map[string]interface{}) for chainId, v := range msg.Distributions { - items := make([]map[string]interface{}, len(v), len(v)) + items := make([]map[string]interface{}, len(v)) for idx, item := range v { items[idx] = item.toNativeMap() } @@ -1016,7 +1016,7 @@ func (msg *Distribution) toNativeMap() map[string]interface{} { native["valTokens"] = msg.ValTokens native["totalReward"] = msg.TotalReward native["commission"] = msg.Commission - as := make([]map[string]interface{}, len(msg.Rewards), len(msg.Rewards)) + as := make([]map[string]interface{}, len(msg.Rewards)) for idx, reward := range msg.Rewards { as[idx] = reward.toNativeMap() } @@ -1064,7 +1064,7 @@ func (msg *SlashMsg) ToNativeMap() map[string]interface{} { slashData := make(map[string]interface{}) for chainId, v := range msg.SlashData { - items := make([]map[string]interface{}, len(v), len(v)) + items := make([]map[string]interface{}, len(v)) for idx, item := range v { items[idx] = item.toNativeMap() } @@ -1123,7 +1123,7 @@ func (msg *Slash) toNativeMap() map[string]interface{} { } native["submitterReward"] = msg.SubmitterReward - vsc := make([]map[string]interface{}, len(msg.ValidatorsCompensation), len(msg.ValidatorsCompensation)) + vsc := make([]map[string]interface{}, len(msg.ValidatorsCompensation)) for idx, compensation := range msg.ValidatorsCompensation { vsc[idx] = compensation.toNativeMap() } diff --git a/app/pub/msgs_cross.go b/app/pub/msgs_cross.go index 619cd391d..4ff46ac00 100644 --- a/app/pub/msgs_cross.go +++ b/app/pub/msgs_cross.go @@ -44,7 +44,7 @@ func (msg CrossTransfer) ToNativeMap() map[string]interface{} { native["contract"] = msg.Contract native["decimals"] = msg.Decimals native["relayerFee"] = msg.RelayerFee - to := make([]map[string]interface{}, len(msg.To), len(msg.To)) + to := make([]map[string]interface{}, len(msg.To)) for idx, t := range msg.To { to[idx] = t.ToNativeMap() } @@ -67,7 +67,7 @@ func (msg CrossTransfers) String() string { func (msg CrossTransfers) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["height"] = msg.Height - transfers := make([]map[string]interface{}, len(msg.Transfers), len(msg.Transfers)) + transfers := make([]map[string]interface{}, len(msg.Transfers)) for idx, t := range msg.Transfers { transfers[idx] = t.ToNativeMap() } diff --git a/app/pub/msgs_mirror.go b/app/pub/msgs_mirror.go index 09d28da3d..8a3eb76ca 100644 --- a/app/pub/msgs_mirror.go +++ b/app/pub/msgs_mirror.go @@ -55,7 +55,7 @@ func (msg Mirrors) String() string { func (msg Mirrors) ToNativeMap() map[string]interface{} { var native = make(map[string]interface{}) native["height"] = msg.Height - mirrors := make([]map[string]interface{}, len(msg.Mirrors), len(msg.Mirrors)) + mirrors := make([]map[string]interface{}, len(msg.Mirrors)) for idx, t := range msg.Mirrors { mirrors[idx] = t.ToNativeMap() } diff --git a/app/pub/msgs_staking.go b/app/pub/msgs_staking.go index d26c12a36..d84f1f574 100644 --- a/app/pub/msgs_staking.go +++ b/app/pub/msgs_staking.go @@ -46,7 +46,7 @@ func (msg *StakingMsg) ToNativeMap() map[string]interface{} { removedValidators := make(map[string]interface{}) for id, v := range msg.RemovedValidators { - rvs := make([]string, len(v), len(v)) + rvs := make([]string, len(v)) for id, rv := range v { rvs[id] = rv.String() } @@ -56,7 +56,7 @@ func (msg *StakingMsg) ToNativeMap() map[string]interface{} { delegations := make(map[string]interface{}) for chainId, v := range msg.Delegations { - dels := make([]map[string]interface{}, len(v), len(v)) + dels := make([]map[string]interface{}, len(v)) for id, vv := range v { dels[id] = vv.toNativeMap() } @@ -67,7 +67,7 @@ func (msg *StakingMsg) ToNativeMap() map[string]interface{} { unBondingDelegations := make(map[string]interface{}) for chainId, v := range msg.UnbondingDelegations { - ubds := make([]map[string]interface{}, len(v), len(v)) + ubds := make([]map[string]interface{}, len(v)) for id, vv := range v { ubds[id] = vv.toNativeMap() } @@ -78,7 +78,7 @@ func (msg *StakingMsg) ToNativeMap() map[string]interface{} { reDelegations := make(map[string]interface{}) for chainId, v := range msg.ReDelegations { - reds := make([]map[string]interface{}, len(v), len(v)) + reds := make([]map[string]interface{}, len(v)) for id, vv := range v { reds[id] = vv.toNativeMap() } @@ -89,7 +89,7 @@ func (msg *StakingMsg) ToNativeMap() map[string]interface{} { completedUBDs := make(map[string]interface{}) for chainId, v := range msg.CompletedUBDs { - cubds := make([]map[string]interface{}, len(v), len(v)) + cubds := make([]map[string]interface{}, len(v)) for id, vv := range v { cubds[id] = vv.toNativeMap() } @@ -100,7 +100,7 @@ func (msg *StakingMsg) ToNativeMap() map[string]interface{} { completedREDs := make(map[string]interface{}) for chainId, v := range msg.CompletedREDs { - creds := make([]map[string]interface{}, len(v), len(v)) + creds := make([]map[string]interface{}, len(v)) for id, vv := range v { creds[id] = vv.toNativeMap() } @@ -111,7 +111,7 @@ func (msg *StakingMsg) ToNativeMap() map[string]interface{} { delegateEvents := make(map[string]interface{}) for chainId, v := range msg.DelegateEvents { - deles := make([]map[string]interface{}, len(v), len(v)) + deles := make([]map[string]interface{}, len(v)) for id, vv := range v { deles[id] = vv.toNativeMap() } @@ -121,7 +121,7 @@ func (msg *StakingMsg) ToNativeMap() map[string]interface{} { unDelegateEvents := make(map[string]interface{}) for chainId, v := range msg.UndelegateEvents { - undeles := make([]map[string]interface{}, len(v), len(v)) + undeles := make([]map[string]interface{}, len(v)) for id, vv := range v { undeles[id] = vv.toNativeMap() } @@ -131,7 +131,7 @@ func (msg *StakingMsg) ToNativeMap() map[string]interface{} { reDelegateEvents := make(map[string]interface{}) for chainId, v := range msg.RedelegateEvents { - redeles := make([]map[string]interface{}, len(v), len(v)) + redeles := make([]map[string]interface{}, len(v)) for id, vv := range v { redeles[id] = vv.toNativeMap() } @@ -141,7 +141,7 @@ func (msg *StakingMsg) ToNativeMap() map[string]interface{} { electedValidators := make(map[string]interface{}) for id, v := range msg.ElectedValidators { - evs := make([]map[string]interface{}, len(v), len(v)) + evs := make([]map[string]interface{}, len(v)) for id, ev := range v { evs[id] = ev.toNativeMap() } diff --git a/app/pub/publisher.go b/app/pub/publisher.go index 31666a574..81d918901 100644 --- a/app/pub/publisher.go +++ b/app/pub/publisher.go @@ -65,7 +65,7 @@ func PublishEvent( if eventData.StakeData != nil { if len(eventData.StakeData.Validators) > 0 { - validators = make([]*Validator, len(eventData.StakeData.Validators), len(eventData.StakeData.Validators)) + validators = make([]*Validator, len(eventData.StakeData.Validators)) msgNum += len(eventData.StakeData.Validators) var i int for _, val := range eventData.StakeData.Validators { @@ -77,7 +77,7 @@ func PublishEvent( if len(eventData.StakeData.RemovedValidators) > 0 { removedValidators = make(map[string][]sdk.ValAddress) for chainId, removedVals := range eventData.StakeData.RemovedValidators { - vals := make([]sdk.ValAddress, len(removedVals), len(removedVals)) + vals := make([]sdk.ValAddress, len(removedVals)) msgNum += len(removedVals) var i int for _, val := range removedVals { @@ -90,7 +90,7 @@ func PublishEvent( if len(eventData.StakeData.Delegations) > 0 || len(eventData.StakeData.RemovedDelegations) > 0 { delegationsMap = make(map[string][]*Delegation) for chainId, dels := range eventData.StakeData.Delegations { - delegations := make([]*Delegation, len(dels), len(dels)) + delegations := make([]*Delegation, len(dels)) msgNum += len(dels) var i int for _, del := range dels { @@ -120,7 +120,7 @@ func PublishEvent( if len(eventData.StakeData.UnbondingDelegations) > 0 { ubdsMap = make(map[string][]*UnbondingDelegation) for chainId, ubds := range eventData.StakeData.UnbondingDelegations { - unbondingDelegations := make([]*UnbondingDelegation, len(ubds), len(ubds)) + unbondingDelegations := make([]*UnbondingDelegation, len(ubds)) msgNum += len(ubds) var i int for _, ubd := range ubds { @@ -134,7 +134,7 @@ func PublishEvent( if len(eventData.StakeData.ReDelegations) > 0 { redsMap = make(map[string][]*ReDelegation) for chainId, reds := range eventData.StakeData.ReDelegations { - redelgations := make([]*ReDelegation, len(reds), len(reds)) + redelgations := make([]*ReDelegation, len(reds)) msgNum += len(reds) var i int for _, red := range reds { @@ -148,7 +148,7 @@ func PublishEvent( if len(eventData.StakeData.CompletedUBDs) > 0 { completedUBDsMap = make(map[string][]*CompletedUnbondingDelegation) for chainId, ubds := range eventData.StakeData.CompletedUBDs { - comUBDs := make([]*CompletedUnbondingDelegation, len(ubds), len(ubds)) + comUBDs := make([]*CompletedUnbondingDelegation, len(ubds)) msgNum += len(ubds) for i, ubd := range ubds { comUBDs[i] = &CompletedUnbondingDelegation{ @@ -163,7 +163,7 @@ func PublishEvent( if len(eventData.StakeData.CompletedREDs) > 0 { completedREDsMap = make(map[string][]*CompletedReDelegation) for chainId, reds := range eventData.StakeData.CompletedREDs { - comREDs := make([]*CompletedReDelegation, len(reds), len(reds)) + comREDs := make([]*CompletedReDelegation, len(reds)) msgNum += len(reds) for i, red := range reds { comREDs[i] = &CompletedReDelegation{ @@ -178,7 +178,7 @@ func PublishEvent( if len(eventData.StakeData.DelegateEvents) > 0 { delegateEventsMap = make(map[string][]*DelegateEvent) for chainId, des := range eventData.StakeData.DelegateEvents { - dess := make([]*DelegateEvent, len(des), len(des)) + dess := make([]*DelegateEvent, len(des)) msgNum += len(des) for i, de := range des { dess[i] = &DelegateEvent{ @@ -197,7 +197,7 @@ func PublishEvent( if len(eventData.StakeData.UndelegateEvents) > 0 { undelegateEventsMap = make(map[string][]*UndelegateEvent) for chainId, v := range eventData.StakeData.UndelegateEvents { - vv := make([]*UndelegateEvent, len(v), len(v)) + vv := make([]*UndelegateEvent, len(v)) msgNum += len(v) for i, ude := range v { vv[i] = &UndelegateEvent{ @@ -216,7 +216,7 @@ func PublishEvent( if len(eventData.StakeData.RedelegateEvents) > 0 { redelegateEventsMap = make(map[string][]*RedelegateEvent) for chainId, v := range eventData.StakeData.RedelegateEvents { - vv := make([]*RedelegateEvent, len(v), len(v)) + vv := make([]*RedelegateEvent, len(v)) msgNum += len(v) for i, ude := range v { vv[i] = &RedelegateEvent{ @@ -237,7 +237,7 @@ func PublishEvent( electedValidatorsMap = make(map[string][]*Validator) for chainId, vals := range eventData.StakeData.ElectedValidators { msgNum += len(vals) - electedVals := make([]*Validator, len(vals), len(vals)) + electedVals := make([]*Validator, len(vals)) for i := range vals { val := Validator(vals[i]) electedVals[i] = &val @@ -272,9 +272,9 @@ func PublishEvent( distributions := make(map[string][]*Distribution) if eventData.StakeData != nil { for chainId, disData := range eventData.StakeData.Distribution { - dis := make([]*Distribution, len(disData), len(disData)) + dis := make([]*Distribution, len(disData)) for i, disData := range disData { - rewards := make([]*Reward, len(disData.Rewards), len(disData.Rewards)) + rewards := make([]*Reward, len(disData.Rewards)) for i, reward := range disData.Rewards { rewardMsg := &Reward{ Validator: reward.ValAddr, @@ -318,7 +318,7 @@ func PublishEvent( var msgNum int slashData := make(map[string][]*Slash) for chainId, slashes := range eventData.SlashData { - slashDataPerChain := make([]*Slash, len(slashes), len(slashes)) + slashDataPerChain := make([]*Slash, len(slashes)) for i, slash := range slashes { vc := make([]*AllocatedAmt, len(slash.ValidatorsCompensation)) @@ -587,7 +587,7 @@ func addClosedOrder(closedToPublish []*Order, toRemoveOrderIdCh chan OrderSymbol } func Stop(publisher MarketDataPublisher) { - if IsLive == false { + if !IsLive { Logger.Error("publication module has already been stopped") return } @@ -628,7 +628,7 @@ func publishAccount(publisher MarketDataPublisher, height int64, timestamp int64 numOfMsgs := len(accountsToPublish) idx := 0 - accs := make([]Account, numOfMsgs, numOfMsgs) + accs := make([]Account, numOfMsgs) for _, acc := range accountsToPublish { if fee, ok := feeToPublish[acc.Owner]; ok { acc.Fee = fee @@ -644,8 +644,8 @@ func publishAccount(publisher MarketDataPublisher, height int64, timestamp int64 func publishOrderBookDelta(publisher MarketDataPublisher, height int64, timestamp int64, changedPriceLevels orderPkg.ChangedPriceLevelsMap) { var deltas []OrderBookDelta for pair, pls := range changedPriceLevels { - buys := make([]PriceLevel, len(pls.Buys), len(pls.Buys)) - sells := make([]PriceLevel, len(pls.Sells), len(pls.Sells)) + buys := make([]PriceLevel, len(pls.Buys)) + sells := make([]PriceLevel, len(pls.Sells)) idx := 0 for price, qty := range pls.Buys { buys[idx] = PriceLevel{price, qty} diff --git a/app/pub/sub/cross.go b/app/pub/sub/cross.go index 60ebccf5c..ec7b5156b 100644 --- a/app/pub/sub/cross.go +++ b/app/pub/sub/cross.go @@ -9,9 +9,9 @@ import ( func SubscribeCrossTransferEvent(sub *pubsub.Subscriber) error { err := sub.Subscribe(bridge.CrossTransferTopic, func(event pubsub.Event) { - switch event.(type) { + switch event := event.(type) { case bridge.CrossTransferEvent: - crossTransferEvent := event.(bridge.CrossTransferEvent) + crossTransferEvent := event if stagingArea.CrossTransferData == nil { stagingArea.CrossTransferData = make([]bridge.CrossTransferEvent, 0, 1) } @@ -27,9 +27,9 @@ func SubscribeCrossTransferEvent(sub *pubsub.Subscriber) error { func SubscribeOracleEvent(sub *pubsub.Subscriber) error { err := sub.Subscribe(oTypes.Topic, func(event pubsub.Event) { - switch event.(type) { + switch event := event.(type) { case oTypes.CrossAppFailEvent: - crossFailEvent := event.(oTypes.CrossAppFailEvent) + crossFailEvent := event sub.Logger.Info("do have crossFailEvent") // no need to publish into CrossTransferData if no balance change. diff --git a/app/pub/sub/mirror.go b/app/pub/sub/mirror.go index f9c6f9b9c..a5fc3e86e 100644 --- a/app/pub/sub/mirror.go +++ b/app/pub/sub/mirror.go @@ -8,9 +8,9 @@ import ( func SubscribeMirrorEvent(sub *pubsub.Subscriber) error { err := sub.Subscribe(bridge.MirrorTopic, func(event pubsub.Event) { - switch event.(type) { + switch event := event.(type) { case bridge.MirrorEvent: - mirrorEvent := event.(bridge.MirrorEvent) + mirrorEvent := event if stagingArea.MirrorData == nil { stagingArea.MirrorData = make([]bridge.MirrorEvent, 0, 1) } diff --git a/app/pub/sub/slash.go b/app/pub/sub/slash.go index 7fca7ce4f..5be13cd4a 100644 --- a/app/pub/sub/slash.go +++ b/app/pub/sub/slash.go @@ -22,9 +22,9 @@ type SlashData struct { func SubscribeSlashEvent(sub *pubsub.Subscriber) error { err := sub.Subscribe(slashing.Topic, func(event pubsub.Event) { - switch event.(type) { + switch event := event.(type) { case slashing.SideSlashEvent: - sideSlashEvent := event.(slashing.SideSlashEvent) + sideSlashEvent := event if toPublish.EventData.SlashData == nil { toPublish.EventData.SlashData = make(map[string][]SlashData) } diff --git a/app/sentryapp.go b/app/sentryapp.go index 442989605..71b0db8c0 100644 --- a/app/sentryapp.go +++ b/app/sentryapp.go @@ -147,11 +147,11 @@ func newMapTxCache(size int) mapTxCache { } } -func (c mapTxCache) size() int { +func (c *mapTxCache) size() int { return len(c.pool) } -func (c mapTxCache) nextRound() { +func (c *mapTxCache) nextRound() { c.mtx.Lock() defer c.mtx.Unlock() victims := make([]string, 0) @@ -170,18 +170,18 @@ func (c mapTxCache) nextRound() { } } -func (c mapTxCache) add(hash string) { +func (c *mapTxCache) add(hash string) { c.mtx.Lock() defer c.mtx.Unlock() c.pool[hash] = &surviveTx{survive: 1, rechecked: true} } -func (c mapTxCache) delete(hash string) { +func (c *mapTxCache) delete(hash string) { c.mtx.Lock() defer c.mtx.Unlock() delete(c.pool, hash) } -func (c mapTxCache) get(hash string) *surviveTx { +func (c *mapTxCache) get(hash string) *surviveTx { return c.pool[hash] } diff --git a/cmd/bnbchaind/init/init.go b/cmd/bnbchaind/init/init.go index 75028d124..ee949ccba 100644 --- a/cmd/bnbchaind/init/init.go +++ b/cmd/bnbchaind/init/init.go @@ -34,8 +34,9 @@ import ( ) const ( - flagOverwrite = "overwrite" - flagClientHome = "home-client" + flagOverwrite = "overwrite" + flagClientHome = "home-client" + //nolint:deadcode,varcheck flagOverwriteKey = "overwrite-key" flagMoniker = "moniker" flagAccPrefix = "acc-prefix" diff --git a/cmd/bnbchaind/init/snapshot.go b/cmd/bnbchaind/init/snapshot.go index 3d7d60724..fd1a2cb89 100644 --- a/cmd/bnbchaind/init/snapshot.go +++ b/cmd/bnbchaind/init/snapshot.go @@ -36,29 +36,32 @@ func SnapshotCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { config := ctx.Config config.SetRoot(viper.GetString(cli.HomeFlag)) appCtx := configPkg.NewDefaultContext() - appCtx.ParseAppConfigInPlace() + err := appCtx.ParseAppConfigInPlace() + if err != nil { + return err + } app.SetUpgradeConfig(appCtx.BinanceChainConfig.UpgradeConfig) logger.Info("setup block db") - blockDB, err := node.DefaultDBProvider(&node.DBContext{"blockstore", config}) + blockDB, err := node.DefaultDBProvider(&node.DBContext{ID: "blockstore", Config: config}) if err != nil { return err } logger.Info("setup state db") - stateDB, err := node.DefaultDBProvider(&node.DBContext{"state", config}) + stateDB, err := node.DefaultDBProvider(&node.DBContext{ID: "state", Config: config}) if err != nil { return err } logger.Info("setup tx db") - txDB, err := node.DefaultDBProvider(&node.DBContext{"tx_index", config}) + txDB, err := node.DefaultDBProvider(&node.DBContext{ID: "tx_index", Config: config}) if err != nil { return err } logger.Info("setup application db") - appDB, err := node.DefaultDBProvider(&node.DBContext{"application", config}) + appDB, err := node.DefaultDBProvider(&node.DBContext{ID: "application", Config: config}) if err != nil { return err } @@ -96,7 +99,7 @@ func SnapshotCmd(ctx *server.Context, cdc *codec.Codec) *cobra.Command { } cmd.Flags().Int64(flagHeight, 0, "specify a syncable height (the height must haven't been pruned") - cmd.MarkFlagRequired(flagHeight) + _ = cmd.MarkFlagRequired(flagHeight) return cmd } diff --git a/cmd/bnbchaind/init/testnet.go b/cmd/bnbchaind/init/testnet.go index 7d4a0fe5a..b6685dfdd 100644 --- a/cmd/bnbchaind/init/testnet.go +++ b/cmd/bnbchaind/init/testnet.go @@ -88,7 +88,7 @@ Example: cmd.Flags().String(client.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") cmd.Flags().StringVar(&app.ServerContext.Bech32PrefixAccAddr, flagAccPrefix, "bnb", "bech32 prefix for AccAddress") - app.ServerContext.BindPFlag("addr.bech32PrefixAccAddr", cmd.Flags().Lookup(flagAccPrefix)) + _ = app.ServerContext.BindPFlag("addr.bech32PrefixAccAddr", cmd.Flags().Lookup(flagAccPrefix)) cmd.Flags().StringSlice(flagMonikers, nil, "specify monikers for nodes if needed") cmd.Flags().String(flagNodeInfoOutputFile, "", "the file containing all node info with json format, if not specified, will just print it") cmd.Flags().StringVar(&app.DefaultKeyPass, "kpass", "12345678", "defaultKeyPass for client keystore") @@ -201,7 +201,10 @@ func createGenesisFiles(cdc *codec.Codec, chainId string, genFiles []string, app } for i := 0; i < len(genTxsJson); i++ { - ExportGenesisFileWithTime(genFiles[i], chainId, nil, appState, genTime) + err = ExportGenesisFileWithTime(genFiles[i], chainId, nil, appState, genTime) + if err != nil { + panic(err) + } } } diff --git a/cmd/bnbchaind/main.go b/cmd/bnbchaind/main.go index f5b50dae3..74b321f04 100644 --- a/cmd/bnbchaind/main.go +++ b/cmd/bnbchaind/main.go @@ -51,5 +51,5 @@ func main() { // prepare and add flags executor := cli.PrepareBaseCmd(rootCmd, "BC", app.DefaultNodeHome) - executor.Execute() + _ = executor.Execute() } diff --git a/cmd/bnbcli/main.go b/cmd/bnbcli/main.go index 508c20dfe..778f7ebfc 100644 --- a/cmd/bnbcli/main.go +++ b/cmd/bnbcli/main.go @@ -102,5 +102,5 @@ func main() { // prepare and add flags executor := cli.PrepareMainCmd(rootCmd, "BC", app.DefaultCLIHome) - executor.Execute() + _ = executor.Execute() } diff --git a/cmd/bnbsentry/main.go b/cmd/bnbsentry/main.go index 854aa67b5..c47f1d03a 100644 --- a/cmd/bnbsentry/main.go +++ b/cmd/bnbsentry/main.go @@ -9,8 +9,6 @@ import ( "github.com/bnb-chain/node/app" ) -const flagSequentialABCI = "seq-abci" - func main() { cdc := app.Codec ctx := app.ServerContext @@ -30,5 +28,5 @@ func main() { // prepare and add flags executor := cli.PrepareBaseCmd(rootCmd, "BC", app.DefaultNodeHome) - executor.Execute() + _ = executor.Execute() } diff --git a/cmd/dexperf/main.go b/cmd/dexperf/main.go index 2ad0f03b5..5ecefb626 100644 --- a/cmd/dexperf/main.go +++ b/cmd/dexperf/main.go @@ -1,3 +1,4 @@ +//nolint package main import ( diff --git a/cmd/pressuremaker/main.go b/cmd/pressuremaker/main.go index e70491c75..6c6ea0fcf 100644 --- a/cmd/pressuremaker/main.go +++ b/cmd/pressuremaker/main.go @@ -70,7 +70,10 @@ func initConfig() { fmt.Println("Can't read config:", err) os.Exit(1) } - viper.Unmarshal(&cfg) + if err := viper.Unmarshal(&cfg); err != nil { + fmt.Println("Can't unmarshal config:", err) + os.Exit(1) + } } var rootCmd = &cobra.Command{ diff --git a/cmd/pressuremaker/utils/utils.go b/cmd/pressuremaker/utils/utils.go index 4858fd27b..0887c4692 100644 --- a/cmd/pressuremaker/utils/utils.go +++ b/cmd/pressuremaker/utils/utils.go @@ -1,3 +1,4 @@ +//nolint package utils import ( diff --git a/common/log/async_file_writer.go b/common/log/async_file_writer.go index cfec2a97c..f145daaa9 100644 --- a/common/log/async_file_writer.go +++ b/common/log/async_file_writer.go @@ -153,7 +153,7 @@ func (w *AsyncFileWriter) flushBuffer() { func (w *AsyncFileWriter) SyncWrite(msg []byte) { w.rotateFile() if w.fd != nil { - w.fd.Write(msg) + _, _ = w.fd.Write(msg) } } diff --git a/common/log/logger.go b/common/log/logger.go index 329900e6b..78e11b65a 100644 --- a/common/log/logger.go +++ b/common/log/logger.go @@ -30,7 +30,10 @@ func NewAsyncFileLogger(filePath string, buffSize int64) tmlog.Logger { } fileWriter = NewAsyncFileWriter(filePath, buffSize) - fileWriter.Start() + err := fileWriter.Start() + if err != nil { + panic(err) + } return tmlog.NewTMLogger(fileWriter) } diff --git a/common/testutils/testutils.go b/common/testutils/testutils.go index 355467a89..5a7f19b18 100644 --- a/common/testutils/testutils.go +++ b/common/testutils/testutils.go @@ -32,7 +32,10 @@ func SetupMultiStoreWithDBForUnitTest() (dbm.DB, sdk.MultiStore, *sdk.KVStoreKey ms.MountStoreWithDB(capKey2, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(capKey3, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(common.PairStoreKey, sdk.StoreTypeIAVL, db) - ms.LoadLatestVersion() + err := ms.LoadLatestVersion() + if err != nil { + panic(err) + } return db, ms, capKey, capKey2, capKey3 } @@ -53,7 +56,7 @@ func PrivAndAddr() (crypto.PrivKey, sdk.AccAddress) { func NewAccount(ctx sdk.Context, am auth.AccountKeeper, free int64) (crypto.PrivKey, sdk.Account) { privKey, addr := PrivAndAddr() acc := am.NewAccountWithAddress(ctx, addr) - acc.SetCoins(NewNativeTokens(free)) + _ = acc.SetCoins(NewNativeTokens(free)) am.SetAccount(ctx, acc) return privKey, acc } @@ -61,7 +64,7 @@ func NewAccount(ctx sdk.Context, am auth.AccountKeeper, free int64) (crypto.Priv func NewNamedAccount(ctx sdk.Context, am auth.AccountKeeper, free int64) (crypto.PrivKey, types.NamedAccount) { privKey, addr := PrivAndAddr() acc := am.NewAccountWithAddress(ctx, addr) - acc.SetCoins(NewNativeTokens(free)) + _ = acc.SetCoins(NewNativeTokens(free)) baseAcc := auth.BaseAccount{ Address: acc.GetAddress(), @@ -84,7 +87,7 @@ func NewAccountForPub(ctx sdk.Context, am auth.AccountKeeper, free, locked, free acc := am.NewAccountWithAddress(ctx, addr) coins := NewNativeTokens(free) coins = append(coins, sdk.NewCoin(symbol, free)) - acc.SetCoins(coins) + _ = acc.SetCoins(coins) appAcc := acc.(*types.AppAccount) lockedCoins := NewNativeTokens(locked) diff --git a/common/types/token.go b/common/types/token.go index 34277c876..02cf28682 100644 --- a/common/types/token.go +++ b/common/types/token.go @@ -141,9 +141,7 @@ func ValidateIssueSymbol(symbol string) error { return errors.New("token symbol cannot be empty") } - if strings.HasSuffix(symbol, TokenSymbolDotBSuffix) { - symbol = strings.TrimSuffix(symbol, TokenSymbolDotBSuffix) - } + symbol = strings.TrimSuffix(symbol, TokenSymbolDotBSuffix) // check len without .B suffix symbolLen := len(symbol) @@ -196,9 +194,7 @@ func ValidateTokenSymbol(symbol string) error { return errors.New("native token symbol should not be suffixed with tx hash") } - if strings.HasSuffix(symbolPart, TokenSymbolDotBSuffix) { - symbolPart = strings.TrimSuffix(symbolPart, TokenSymbolDotBSuffix) - } + symbolPart = strings.TrimSuffix(symbolPart, TokenSymbolDotBSuffix) // check len without .B suffix // This function is used by both client and server side, and the client needs to use TokenSymbolNewMinLen for the validation. diff --git a/common/utils/ring.go b/common/utils/ring.go index d5429d23c..d4328a963 100644 --- a/common/utils/ring.go +++ b/common/utils/ring.go @@ -14,7 +14,7 @@ type FixedSizeRing struct { func NewFixedSizedRing(cap int64) *FixedSizeRing { return &FixedSizeRing{ - buf: make([]interface{}, cap, cap), + buf: make([]interface{}, cap), tail: 0, size: 0, cap: cap, diff --git a/networks/tools/account_viewer/account_viewer.go b/networks/tools/account_viewer/account_viewer.go index f48421c21..9a81d1b7f 100644 --- a/networks/tools/account_viewer/account_viewer.go +++ b/networks/tools/account_viewer/account_viewer.go @@ -44,6 +44,7 @@ func openAppDB(root string) *db.GoLevelDB { return openDB(root, "application") } +//nolint:unused,deadcode func getState(root string) state.State { stateDb := openDB(root, "state") defer stateDb.Close() @@ -65,6 +66,7 @@ func prepareCms(root string, appDB *db.GoLevelDB, height int64) sdk.CommitMultiS return cms } +//nolint:unused,deadcode func accountKeyDecoder(key []byte) string { prefix := []byte("account:") key = key[len(prefix):] @@ -73,7 +75,10 @@ func accountKeyDecoder(key []byte) string { func accountValueDecoder(value []byte) interface{} { acc := types.AppAccount{} - codec.UnmarshalBinaryBare(value, &acc) + err := codec.UnmarshalBinaryBare(value, &acc) + if err != nil { + panic(err) + } return acc } @@ -95,7 +100,7 @@ func getAccountNumber(height int64, root string) { } tree.Iterate(func(key []byte, value []byte) bool { - if bytes.Compare([]byte("globalAccountNumber"), key) != 0 { + if !bytes.Equal([]byte("globalAccountNumber"), key) { num++ accNum := accountValueDecoder(value).(types.AppAccount).AccountNumber if accNum > maxAccountNum { @@ -135,7 +140,7 @@ func getNode(key []byte, cms sdk.CommitMultiStore) *iavl.Node { var innerGetNode func(key []byte, node *iavl.Node, t *iavl.ImmutableTree) *iavl.Node innerGetNode = func(key []byte, node *iavl.Node, t *iavl.ImmutableTree) *iavl.Node { if iavl.IsLeaf(node) { - if bytes.Compare(iavl.Key(node), key) != 0 { + if !bytes.Equal(iavl.Key(node), key) { return nil } else { return node @@ -174,7 +179,7 @@ func analysisAccByNum(height, accNum int64, home string) { if height > 0 { prevAccState = getAccByNum(home, height-1, accNum) if prevAccState.Address == nil { - fmt.Println(fmt.Sprintf("acc number %v does not exist", accNum)) + fmt.Printf("acc number %v does not exist\n", accNum) return } } diff --git a/networks/tools/compare/compare.go b/networks/tools/compare/compare.go index c0bbbd670..2628fe4ff 100644 --- a/networks/tools/compare/compare.go +++ b/networks/tools/compare/compare.go @@ -77,7 +77,11 @@ func accountKeyDecoder(key []byte) string { func accountValueDecoder(value []byte) interface{} { acc := types.AppAccount{} - codec.UnmarshalBinaryBare(value, &acc) + err := codec.UnmarshalBinaryBare(value, &acc) + if err != nil { + fmt.Printf("unmarshal account %v err: %s\n", value, err) + panic(err) + } return acc } @@ -140,9 +144,6 @@ func diff(node1 *iavl.Node, tree1 *iavl.ImmutableTree, } else if iavl.IsLeaf(node1) || iavl.IsLeaf(node2) { fmt.Println("node1 and node2 have different hierarchy") return - } else { - // ignore inner nodes - // fmt.Printf("\t%s\n<=> %s\n", node1, node2) } diff(iavl.GetLeftNode(node1, tree1), tree1, iavl.GetLeftNode(node2, tree2), tree2, keyDecoder, valueDecoder) diff(iavl.GetRightNode(node1, tree1), tree1, iavl.GetRightNode(node2, tree2), tree2, keyDecoder, valueDecoder) @@ -201,7 +202,7 @@ func getNode(key []byte, cms sdk.CommitMultiStore) *iavl.Node { var innerGetNode func(key []byte, node *iavl.Node, t *iavl.ImmutableTree) *iavl.Node innerGetNode = func(key []byte, node *iavl.Node, t *iavl.ImmutableTree) *iavl.Node { if iavl.IsLeaf(node) { - if bytes.Compare(iavl.Key(node), key) != 0 { + if !bytes.Equal(iavl.Key(node), key) { return nil } else { return node diff --git a/networks/tools/snapshot_viewer/snapshot.go b/networks/tools/snapshot_viewer/snapshot.go index 8ba859aff..9b59891b0 100644 --- a/networks/tools/snapshot_viewer/snapshot.go +++ b/networks/tools/snapshot_viewer/snapshot.go @@ -93,7 +93,7 @@ func getSnapshot(height int64, root string) (obs map[string]order.OrderBookSnaps panic(fmt.Sprintf("failed to unmarshal snapshort for orderbook [%s]", string(iter.Key()))) } obs[string(iter.Key())] = ob - fmt.Println(fmt.Sprintf("%#v", ob)) + fmt.Printf("%#v\n", ob) } activeOrderKeyPrefix := genActiveOrdersSnapshotKey(height) @@ -110,7 +110,7 @@ func getSnapshot(height int64, root string) (obs map[string]order.OrderBookSnaps //fmt.Println(fmt.Sprintf("%#v", ao)) fmt.Println("active orders") for _, oi := range ao.Orders { - fmt.Println(fmt.Sprintf("%#v", oi)) + fmt.Printf("%#v\n", oi) } fmt.Println("order book size", obSize) fmt.Println("active order size", aoSize) diff --git a/networks/tools/state_recover/state_recover.go b/networks/tools/state_recover/state_recover.go index ac59dd14d..e72f22444 100644 --- a/networks/tools/state_recover/state_recover.go +++ b/networks/tools/state_recover/state_recover.go @@ -52,6 +52,7 @@ func calcValidatorsKey(height int64) []byte { return []byte(fmt.Sprintf("validatorsKey:%v", height)) } +//nolint:deadcode,unused func calcConsensusParamsKey(height int64) []byte { return []byte(fmt.Sprintf("consensusParamsKey:%v", height)) } @@ -102,17 +103,17 @@ func resetBlockChainState(height int64, rootDir string) { blockState.LastBlockTime = block.Time blockState.NextValidators, err = state.LoadValidators(stateDb, height+2) if err != nil { - cmn.Exit(fmt.Sprintf("failed to load validator info")) + cmn.Exit("failed to load validator info") return } blockState.Validators, err = state.LoadValidators(stateDb, height+1) if err != nil { - cmn.Exit(fmt.Sprintf("failed to load validator info")) + cmn.Exit("failed to load validator info") return } blockState.LastValidators, err = state.LoadValidators(stateDb, height) if err != nil { - cmn.Exit(fmt.Sprintf("failed to load validator info")) + cmn.Exit("failed to load validator info") return } blockState.LastHeightConsensusParamsChanged = 1 @@ -122,7 +123,7 @@ func resetBlockChainState(height int64, rootDir string) { } blockState.ConsensusParams, err = state.LoadConsensusParams(stateDb, height) if err != nil { - cmn.Exit(fmt.Sprintf("failed to load consensusparam info")) + cmn.Exit("failed to load consensusparam info") return } blockState.LastResultsHash = nextBlock.LastResultsHash @@ -181,6 +182,7 @@ func setLatestVersion(batch db.DB, version int64) { batch.Set([]byte("s/latest"), latestBytes) } +//nolint:deadcode func MountStoresIAVL(cms store.CommitMultiStore, keys ...*sdk.KVStoreKey) { for _, key := range keys { cms.MountStoreWithDB(key, sdk.StoreTypeIAVL, nil) diff --git a/plugins/api/handlers.go b/plugins/api/handlers.go index ff32d4550..e09792307 100644 --- a/plugins/api/handlers.go +++ b/plugins/api/handlers.go @@ -47,6 +47,7 @@ func (s *server) withUrlEncForm(next http.HandlerFunc) http.HandlerFunc { } } +//nolint:unused // withMultipartForm parses multipart/form-data forms func (s *server) withMultipartForm(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { diff --git a/plugins/api/handlers/account.go b/plugins/api/handlers/account.go index a3ee971bd..8f948271f 100644 --- a/plugins/api/handlers/account.go +++ b/plugins/api/handlers/account.go @@ -34,8 +34,7 @@ func AccountReqHandler(cdc *wire.Codec, ctx context.CLIContext) http.HandlerFunc throw := func(w http.ResponseWriter, status int, message string) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(message)) - return + _, _ = w.Write([]byte(message)) } return func(w http.ResponseWriter, r *http.Request) { @@ -78,7 +77,7 @@ func AccountReqHandler(cdc *wire.Codec, ctx context.CLIContext) http.HandlerFunc w.Header().Set("Content-Type", responseType) w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(resp) + _ = json.NewEncoder(w).Encode(resp) } } @@ -104,7 +103,7 @@ func toTokenBalances(acc *types.AppAccount) []tkclient.TokenBalance { } } - res := make([]tkclient.TokenBalance, len(balances), len(balances)) + res := make([]tkclient.TokenBalance, len(balances)) i := 0 for _, balance := range balances { res[i] = *balance diff --git a/plugins/api/handlers/simulate.go b/plugins/api/handlers/simulate.go index adca24a0d..c8f62766c 100644 --- a/plugins/api/handlers/simulate.go +++ b/plugins/api/handlers/simulate.go @@ -21,8 +21,7 @@ func SimulateReqHandler(cdc *wire.Codec, ctx context.CLIContext) http.HandlerFun throw := func(w http.ResponseWriter, status int, message string) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(message)) - return + _, _ = w.Write([]byte(message)) } return func(w http.ResponseWriter, r *http.Request) { @@ -68,6 +67,6 @@ func SimulateReqHandler(cdc *wire.Codec, ctx context.CLIContext) http.HandlerFun w.Header().Set("Content-Type", responseType) w.WriteHeader(http.StatusOK) - w.Write(output) + _, _ = w.Write(output) } } diff --git a/plugins/api/handlers/stake.go b/plugins/api/handlers/stake.go index 9ecfa37c4..67730227d 100644 --- a/plugins/api/handlers/stake.go +++ b/plugins/api/handlers/stake.go @@ -62,8 +62,7 @@ func ValidatorQueryReqHandler(cdc *wire.Codec, ctx context.CLIContext) http.Hand throw := func(w http.ResponseWriter, status int, message string) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(message)) - return + _, _ = w.Write([]byte(message)) } return func(w http.ResponseWriter, r *http.Request) { @@ -83,7 +82,7 @@ func ValidatorQueryReqHandler(cdc *wire.Codec, ctx context.CLIContext) http.Hand w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(convertToValidatorOutputs(validators)) + _ = json.NewEncoder(w).Encode(convertToValidatorOutputs(validators)) } } @@ -93,8 +92,7 @@ func DelegatorUnbondindDelegationsQueryReqHandler(cdc *wire.Codec, ctx context.C throw := func(w http.ResponseWriter, status int, message string) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(message)) - return + _, _ = w.Write([]byte(message)) } return func(w http.ResponseWriter, r *http.Request) { @@ -131,6 +129,6 @@ func DelegatorUnbondindDelegationsQueryReqHandler(cdc *wire.Codec, ctx context.C w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(unbondingDelegations) + _ = json.NewEncoder(w).Encode(unbondingDelegations) } } diff --git a/plugins/api/handlers/version.go b/plugins/api/handlers/version.go index fd66a8bff..c5c384eee 100644 --- a/plugins/api/handlers/version.go +++ b/plugins/api/handlers/version.go @@ -12,7 +12,7 @@ import ( // CLIVersionReqHandler handles requests to the cli version REST handler endpoint func CLIVersionReqHandler(w http.ResponseWriter, r *http.Request) { v := version.GetVersion() - w.Write([]byte(v)) + _, _ = w.Write([]byte(v)) } // NodeVersionReqHandler handles requests to the connected node version REST handler endpoint @@ -21,9 +21,9 @@ func NodeVersionReqHandler(ctx context.CLIContext) http.HandlerFunc { version, err := ctx.Query("/app/version", nil) if err != nil { w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(fmt.Sprintf("Could't query version. Error: %s", err.Error()))) + _, _ = w.Write([]byte(fmt.Sprintf("Could't query version. Error: %s", err.Error()))) return } - w.Write(version) + _, _ = w.Write(version) } } diff --git a/plugins/bridge/cross_app.go b/plugins/bridge/cross_app.go index 8e15a59ba..9e18bee34 100644 --- a/plugins/bridge/cross_app.go +++ b/plugins/bridge/cross_app.go @@ -102,7 +102,7 @@ func (app *BindApp) ExecuteSynPackage(ctx sdk.Context, payload []byte, relayerFe if sdkErr != nil { log.With("module", "bridge").Error("update token info error", "err", sdkErr.Error(), "symbol", symbol) return sdk.ExecuteResult{ - Err: sdk.ErrInternal(fmt.Sprintf("update token bind info error")), + Err: sdk.ErrInternal("update token bind info error"), } } @@ -438,7 +438,7 @@ func (app *TransferInApp) ExecuteSynPackage(ctx sdk.Context, payload []byte, rel } // emit peg related event - var totalAmount int64 = 0 + var totalAmount int64 tags := types.GenerateTransferInTags(transferInPackage.ReceiverAddresses, symbol, transferInPackage.Amounts, false) if totalTransferInAmount != nil { totalAmount = totalTransferInAmount.AmountOf(symbol) diff --git a/plugins/bridge/types/msgs.go b/plugins/bridge/types/msgs.go index bd4f79871..5582885a2 100644 --- a/plugins/bridge/types/msgs.go +++ b/plugins/bridge/types/msgs.go @@ -72,7 +72,7 @@ func (msg BindMsg) ValidateBasic() sdk.Error { } if msg.ContractDecimals < 0 { - return ErrInvalidDecimals(fmt.Sprintf("decimals should be no less than 0")) + return ErrInvalidDecimals("decimals should be no less than 0") } if msg.ExpireTime <= 0 { diff --git a/plugins/bridge/types/serialize.go b/plugins/bridge/types/serialize.go index 337bc5912..fe44863f6 100644 --- a/plugins/bridge/types/serialize.go +++ b/plugins/bridge/types/serialize.go @@ -210,7 +210,7 @@ func SymbolToBytes(symbol string) [32]byte { } func BytesToSymbol(symbolBytes [32]byte) string { - tokenSymbolBytes := make([]byte, 32, 32) + tokenSymbolBytes := make([]byte, 32) copy(tokenSymbolBytes[:], symbolBytes[:]) return string(bytes.Trim(tokenSymbolBytes, "\x00")) } diff --git a/plugins/dex/abci.go b/plugins/dex/abci.go index 2d4eca25c..cda79dbfa 100644 --- a/plugins/dex/abci.go +++ b/plugins/dex/abci.go @@ -39,7 +39,7 @@ func createAbciQueryHandler(keeper *DexKeeper, abciQueryPrefix string) app.AbciQ pairs := listPairs(keeper, ctx, queryPrefix) var offset, limit, end int var err error - if pairs == nil || len(pairs) == 0 { + if len(pairs) == 0 { pairs = make([]types.TradingPair, 0) goto respond } diff --git a/plugins/dex/client/rest/getdepth.go b/plugins/dex/client/rest/getdepth.go index 9d0f8d260..818034476 100644 --- a/plugins/dex/client/rest/getdepth.go +++ b/plugins/dex/client/rest/getdepth.go @@ -27,8 +27,7 @@ func DepthReqHandler(cdc *wire.Codec, ctx context.CLIContext) http.HandlerFunc { throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } return func(w http.ResponseWriter, r *http.Request) { diff --git a/plugins/dex/client/rest/getpairs.go b/plugins/dex/client/rest/getpairs.go index 89181ec26..8288a34fe 100644 --- a/plugins/dex/client/rest/getpairs.go +++ b/plugins/dex/client/rest/getpairs.go @@ -23,7 +23,7 @@ func listAllTradingPairs(ctx context.CLIContext, cdc *wire.Codec, prefix string, } pairs := make([]types.TradingPair, 0) err = cdc.UnmarshalBinaryLengthPrefixed(bz, &pairs) - return pairs, nil + return pairs, err } // GetPairsReqHandler creates an http request handler to list @@ -38,8 +38,7 @@ func GetPairsReqHandler(cdc *wire.Codec, ctx context.CLIContext, abciQueryPrefix throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } return func(w http.ResponseWriter, r *http.Request) { @@ -97,6 +96,6 @@ func GetPairsReqHandler(cdc *wire.Codec, ctx context.CLIContext, abciQueryPrefix w.Header().Set("Content-Type", responseType) w.WriteHeader(http.StatusOK) - w.Write(output) + _, _ = w.Write(output) } } diff --git a/plugins/dex/client/rest/openorders.go b/plugins/dex/client/rest/openorders.go index bc1cebdc4..248347675 100644 --- a/plugins/dex/client/rest/openorders.go +++ b/plugins/dex/client/rest/openorders.go @@ -17,8 +17,7 @@ func OpenOrdersReqHandler(cdc *wire.Codec, ctx context.CLIContext) http.HandlerF throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } return func(w http.ResponseWriter, r *http.Request) { symbol := r.FormValue("symbol") diff --git a/plugins/dex/client/rest/putorder.go b/plugins/dex/client/rest/putorder.go index 01b6e6df1..22ad35f1b 100644 --- a/plugins/dex/client/rest/putorder.go +++ b/plugins/dex/client/rest/putorder.go @@ -60,8 +60,7 @@ func PutOrderReqHandler(cdc *wire.Codec, ctx context.CLIContext, accStoreName st throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } accDecoder := authcmd.GetAccountDecoder(cdc) return func(w http.ResponseWriter, r *http.Request) { @@ -167,6 +166,6 @@ func PutOrderReqHandler(cdc *wire.Codec, ctx context.CLIContext, accStoreName st w.Header().Set("Content-Type", responseType) w.WriteHeader(http.StatusOK) - w.Write(output) + _, _ = w.Write(output) } } diff --git a/plugins/dex/matcheng/engine.go b/plugins/dex/matcheng/engine.go index 925beeab5..bcf6e5b64 100644 --- a/plugins/dex/matcheng/engine.go +++ b/plugins/dex/matcheng/engine.go @@ -242,7 +242,10 @@ func (me *MatchEng) DropFilledOrder() (droppedIds []string) { me.Book.RemovePriceLevel(p.Price, BUYSIDE) } else { for i := toRemoveStartIdx; i < toRemoveEndIdx; i++ { - me.Book.RemoveOrder(droppedIds[i], BUYSIDE, p.Price) + _, err := me.Book.RemoveOrder(droppedIds[i], BUYSIDE, p.Price) + if err != nil { + panic(err) + } } } } @@ -259,7 +262,10 @@ func (me *MatchEng) DropFilledOrder() (droppedIds []string) { me.Book.RemovePriceLevel(p.Price, SELLSIDE) } else { for i := toRemoveStartIdx; i < toRemoveEndIdx; i++ { - me.Book.RemoveOrder(droppedIds[i], SELLSIDE, p.Price) + _, err := me.Book.RemoveOrder(droppedIds[i], SELLSIDE, p.Price) + if err != nil { + panic(err) + } } } } diff --git a/plugins/dex/matcheng/match.go b/plugins/dex/matcheng/match.go index ff3cf3006..4ef47ed6d 100644 --- a/plugins/dex/matcheng/match.go +++ b/plugins/dex/matcheng/match.go @@ -257,10 +257,7 @@ func allocateResidual(toAlloc *int64, orders []OrderPart, lotSize int64) bool { *toAlloc = residual //assert *toAlloc == 0 - if compareBuy(*toAlloc, 0) != 0 { - return false - } - return true + return compareBuy(*toAlloc, 0) == 0 } // totalLot * orderLeft / totalLeft, orderLeft <= totalLeft diff --git a/plugins/dex/matcheng/orderbook.go b/plugins/dex/matcheng/orderbook.go index 27450d3d7..cacf521bf 100644 --- a/plugins/dex/matcheng/orderbook.go +++ b/plugins/dex/matcheng/orderbook.go @@ -315,6 +315,7 @@ func toPriceLevel(pi PriceLevelInterface, side int8) *PriceLevel { return nil } +//nolint:deadcode,unused func printOrderQueueString(q *bt.BTree, side int8) string { var buffer bytes.Buffer q.Ascend(func(i bt.Item) bool { diff --git a/plugins/dex/matcheng/types.go b/plugins/dex/matcheng/types.go index fbf87e3a0..c25de1c85 100644 --- a/plugins/dex/matcheng/types.go +++ b/plugins/dex/matcheng/types.go @@ -221,7 +221,3 @@ func (l *MergedPriceLevel) AddOrders(orders []*OrderPart) { type TakerSideOrders struct { *MergedPriceLevel } - -func (m TakerSideOrders) length() int { - return len(m.orders) -} diff --git a/plugins/dex/order/fee.go b/plugins/dex/order/fee.go index fb3a6e24e..fda994db3 100644 --- a/plugins/dex/order/fee.go +++ b/plugins/dex/order/fee.go @@ -296,10 +296,6 @@ func dexFeeWrap(fee sdk.Coin) sdk.Fee { return sdk.NewFee(sdk.Coins{fee}, sdk.FeeForProposer) } -func isNativeToken(symbol string) bool { - return symbol == types.NativeTokenSymbol -} - func (m *FeeManager) ExpireFees() (int64, int64) { return m.FeeConfig.ExpireFeeNative, m.FeeConfig.ExpireFee } diff --git a/plugins/dex/order/handler.go b/plugins/dex/order/handler.go index f4c0937b6..4eda0aaa1 100644 --- a/plugins/dex/order/handler.go +++ b/plugins/dex/order/handler.go @@ -92,7 +92,7 @@ func validateQtyAndLockBalance(ctx sdk.Context, keeper *DexKeeper, acc common.Na toLockCoins = sdk.Coins{{Denom: baseAssetSymbol, Amount: msg.Quantity}} } - acc.SetCoins(freeBalance.Minus(toLockCoins)) + _ = acc.SetCoins(freeBalance.Minus(toLockCoins)) acc.SetLockedCoins(acc.GetLockedCoins().Plus(toLockCoins)) keeper.am.SetAccount(ctx, acc) return nil @@ -203,7 +203,7 @@ func handleCancelOrder( if !transfer.FeeFree() { acc := dexKeeper.am.GetAccount(ctx, msg.Sender) fee = dexKeeper.FeeManager.CalcFixedFee(acc.GetCoins(), transfer.eventType, transfer.inAsset, dexKeeper.GetEngines()) - acc.SetCoins(acc.GetCoins().Minus(fee.Tokens)) + _ = acc.SetCoins(acc.GetCoins().Minus(fee.Tokens)) dexKeeper.am.SetAccount(ctx, acc) } diff --git a/plugins/dex/order/keeper.go b/plugins/dex/order/keeper.go index 805a2f5f3..1c26f63d4 100644 --- a/plugins/dex/order/keeper.go +++ b/plugins/dex/order/keeper.go @@ -1,3 +1,4 @@ +//nolint:errcheck package order import ( diff --git a/plugins/dex/order/keeper_match.go b/plugins/dex/order/keeper_match.go index 48b7cd4bc..0b520fed6 100644 --- a/plugins/dex/order/keeper_match.go +++ b/plugins/dex/order/keeper_match.go @@ -160,8 +160,7 @@ func (kp *DexKeeper) matchAndDistributeTradesForSymbol(symbol string, height, ti } return // no need to handle IOC } - var iocIDs []string - iocIDs = orderKeeper.getRoundIOCOrdersForPair(symbol) + iocIDs := orderKeeper.getRoundIOCOrdersForPair(symbol) for _, id := range iocIDs { if msg, ok := orders[id]; ok { delete(orders, id) diff --git a/plugins/dex/order/keeper_recovery.go b/plugins/dex/order/keeper_recovery.go index 10ec822cd..b899b89e3 100644 --- a/plugins/dex/order/keeper_recovery.go +++ b/plugins/dex/order/keeper_recovery.go @@ -67,8 +67,7 @@ func (kp *DexKeeper) SnapShotOrderBook(ctx sdk.Context, height int64) (effectedS effectedStoreKeys = make([]string, 0) for pair, eng := range kp.engines { buys, sells := eng.Book.GetAllLevels() - var snapshot OrderBookSnapshot - snapshot = OrderBookSnapshot{Buys: buys, Sells: sells, LastTradePrice: eng.LastTradePrice} + snapshot := OrderBookSnapshot{Buys: buys, Sells: sells, LastTradePrice: eng.LastTradePrice} if sdk.IsUpgrade(upgrade.BEP8) { snapshot.LastMatchHeight = eng.LastMatchHeight } @@ -91,7 +90,7 @@ func (kp *DexKeeper) SnapShotOrderBook(ctx sdk.Context, height int64) (effectedS } } sort.Strings(msgKeys) - msgs := make([]OrderInfo, len(msgKeys), len(msgKeys)) + msgs := make([]OrderInfo, len(msgKeys)) for i, key := range msgKeys { msgs[i] = *allOrders[idSymbolMap[key]][key] } @@ -139,19 +138,28 @@ func (kp *DexKeeper) LoadOrderBookSnapshot(ctx sdk.Context, latestBlockHeight in var bw bytes.Buffer r, err := zlib.NewReader(b) if err != nil { - panic(fmt.Sprintf("failed to unzip snapshort for orderbook [%s]", key)) + panic(fmt.Sprintf("failed to unzip snapshort for orderbook [%s], err: %v", key, err)) + } + _, err = io.Copy(&bw, r) + if err != nil { + panic(fmt.Sprintf("failed to unzip snapshort for orderbook [%s]: err: %v", key, err)) } - io.Copy(&bw, r) var ob OrderBookSnapshot err = kp.cdc.UnmarshalBinaryLengthPrefixed(bw.Bytes(), &ob) if err != nil { panic(fmt.Sprintf("failed to unmarshal snapshort for orderbook [%s]", key)) } for _, pl := range ob.Buys { - eng.Book.InsertPriceLevel(&pl, me.BUYSIDE) + err := eng.Book.InsertPriceLevel(&pl, me.BUYSIDE) + if err != nil { + panic(fmt.Sprintf("failed to insert buy price level [%s], err: %v", key, err)) + } } for _, pl := range ob.Sells { - eng.Book.InsertPriceLevel(&pl, me.SELLSIDE) + err := eng.Book.InsertPriceLevel(&pl, me.SELLSIDE) + if err != nil { + panic(fmt.Sprintf("failed to insert sell price level [%s], err: %v", key, err)) + } } eng.LastTradePrice = ob.LastTradePrice if sdk.IsUpgrade(upgrade.BEP8) { @@ -173,7 +181,10 @@ func (kp *DexKeeper) LoadOrderBookSnapshot(ctx sdk.Context, latestBlockHeight in if err != nil { panic(fmt.Sprintf("failed to unmarshal snapshort for active order [%s]", key)) } - io.Copy(&bw, r) + _, err = io.Copy(&bw, r) + if err != nil { + panic(fmt.Sprintf("failed to unmarshal snapshort for active order [%s]: err: %v", key, err)) + } var ao ActiveOrders err = kp.cdc.UnmarshalBinaryLengthPrefixed(bw.Bytes(), &ao) if err != nil { @@ -230,7 +241,10 @@ func (kp *DexKeeper) replayOneBlocks(logger log.Logger, block *tmtypes.Block, st height, t, height, t, 0, txHash.String(), txSource} - kp.AddOrder(orderInfo, true) + err := kp.AddOrder(orderInfo, true) + if err != nil { + logger.Error("Failed to replay NreOrderMsg", "err", err) + } logger.Info("Added Order", "order", msg) case CancelOrderMsg: err := kp.RemoveOrder(msg.RefId, msg.Symbol, func(ord me.OrderPart) { diff --git a/plugins/dex/order/mini_keeper.go b/plugins/dex/order/mini_keeper.go index b0d7b36ec..1b212e6fc 100644 --- a/plugins/dex/order/mini_keeper.go +++ b/plugins/dex/order/mini_keeper.go @@ -70,10 +70,6 @@ func (kp *MiniOrderKeeper) iterateRoundSelectedPairs(iter func(string)) { } } -func (kp *MiniOrderKeeper) getRoundPairsNum() int { - return len(kp.symbolSelector.roundSelectedSymbols) -} - func (kp *MiniOrderKeeper) getRoundOrdersNum() int { n := 0 kp.iterateRoundSelectedPairs(func(symbol string) { diff --git a/plugins/dex/order/msg.go b/plugins/dex/order/msg.go index 941e18972..ff52f507b 100644 --- a/plugins/dex/order/msg.go +++ b/plugins/dex/order/msg.go @@ -145,8 +145,7 @@ func NewNewOrderMsg(sender sdk.AccAddress, id string, side int8, // NewNewOrderMsgAuto constructs a new NewOrderMsg and auto-assigns its order ID func NewNewOrderMsgAuto(txBuilder txbuilder.TxBuilder, sender sdk.AccAddress, side int8, symbol string, price int64, qty int64) (NewOrderMsg, error) { - var id string - id = GenerateOrderID(txBuilder.Sequence+1, sender) + id := GenerateOrderID(txBuilder.Sequence+1, sender) return NewOrderMsg{ Sender: sender, Id: id, diff --git a/plugins/dex/order/order_keeper.go b/plugins/dex/order/order_keeper.go index 3e79c6548..6679a132f 100644 --- a/plugins/dex/order/order_keeper.go +++ b/plugins/dex/order/order_keeper.go @@ -143,15 +143,15 @@ func (kp *BaseOrderKeeper) getOpenOrders(pair string, addr sdk.AccAddress) []sto openOrders = append( openOrders, store.OpenOrder{ - order.Id, - pair, - utils.Fixed8(order.Price), - utils.Fixed8(order.Quantity), - utils.Fixed8(order.CumQty), - order.CreatedHeight, - order.CreatedTimestamp, - order.LastUpdatedHeight, - order.LastUpdatedTimestamp, + Id: order.Id, + Symbol: pair, + Price: utils.Fixed8(order.Price), + Quantity: utils.Fixed8(order.Quantity), + CumQty: utils.Fixed8(order.CumQty), + CreatedHeight: order.CreatedHeight, + CreatedTimestamp: order.CreatedTimestamp, + LastUpdatedHeight: order.LastUpdatedHeight, + LastUpdatedTimestamp: order.LastUpdatedTimestamp, }) } } @@ -272,10 +272,6 @@ func (kp *BEP2OrderKeeper) reloadOrder(symbol string, orderInfo *OrderInfo, heig } } -func (kp *BEP2OrderKeeper) getRoundPairsNum() int { - return len(kp.roundOrders) -} - func (kp *BEP2OrderKeeper) getRoundOrdersNum() int { n := 0 for _, orders := range kp.roundOrders { diff --git a/plugins/dex/order/wal.go b/plugins/dex/order/wal.go index ac7c52064..2cb709817 100644 --- a/plugins/dex/order/wal.go +++ b/plugins/dex/order/wal.go @@ -22,6 +22,7 @@ var NewWALDeccoder = cs.NewWALDecoder const ( // must be greater than 4K orders + // nolint:deadcode,unused,varcheck maxMsgSizeBytes = 4 * 1024 * 1024 // 4MB walFileName = "orderbook_wal" ) @@ -159,13 +160,3 @@ type WALSearchOptions struct { // IgnoreDataCorruptionErrors set to true will result in skipping data corruption errors. IgnoreDataCorruptionErrors bool } - -type nilWAL struct{} - -func (nilWAL) Write(m WALMessage) {} -func (nilWAL) WriteSync(m WALMessage) {} -func (nilWAL) File() *os.File { return nil } - -func (nilWAL) Start() error { return nil } -func (nilWAL) Stop() error { return nil } -func (nilWAL) Wait() {} diff --git a/plugins/dex/plugin.go b/plugins/dex/plugin.go index 5eed835b2..64c646da3 100644 --- a/plugins/dex/plugin.go +++ b/plugins/dex/plugin.go @@ -64,7 +64,6 @@ func EndBreatheBlock(ctx sdk.Context, dexKeeper *DexKeeper, govKeeper gov.Keeper if _, err := dexKeeper.SnapShotOrderBook(ctx, height); err != nil { logger.Error("Failed to snapshot order book", "blockHeight", height, "err", err) } - return } func delistTradingPairs(ctx sdk.Context, govKeeper gov.Keeper, dexKeeper *DexKeeper, blockTime time.Time) { diff --git a/plugins/dex/store/codec.go b/plugins/dex/store/codec.go index 046acfecc..8ed22950b 100644 --- a/plugins/dex/store/codec.go +++ b/plugins/dex/store/codec.go @@ -9,9 +9,8 @@ import ( ) // queryOrderBook queries the store for the serialized order book for a given pair. -func queryOrderBook(cdc *wire.Codec, ctx context.CLIContext, pair string, levels int) (*[]byte, error) { - var path string - path = fmt.Sprintf("dex/orderbook/%s/%d", pair, levels) +func queryOrderBook(_cdc *wire.Codec, ctx context.CLIContext, pair string, levels int) (*[]byte, error) { + path := fmt.Sprintf("dex/orderbook/%s/%d", pair, levels) bz, err := ctx.Query(path, nil) if err != nil { return nil, err @@ -43,8 +42,7 @@ func GetOrderBook(cdc *wire.Codec, ctx context.CLIContext, pair string, levels i } func queryOpenOrders(cdc *wire.Codec, ctx context.CLIContext, pair string, addr string) (*[]byte, error) { - var path string - path = fmt.Sprintf("dex/openorders/%s/%s", pair, addr) + path := fmt.Sprintf("dex/openorders/%s/%s", pair, addr) if bz, err := ctx.Query(path, nil); err != nil { return nil, err } else { diff --git a/plugins/dex/store/mapper.go b/plugins/dex/store/mapper.go index d184726f6..80d717770 100644 --- a/plugins/dex/store/mapper.go +++ b/plugins/dex/store/mapper.go @@ -196,7 +196,7 @@ func (m mapper) encodeRecentPrices(recentPrices map[string]int64) []byte { numSymbol := len(recentPrices) symbols := make([]string, numSymbol) i := 0 - for symbol, _ := range recentPrices { + for symbol := range recentPrices { symbols[i] = symbol i++ } diff --git a/plugins/tokens/client/cli/atomic_swap.go b/plugins/tokens/client/cli/atomic_swap.go index a59e7a251..9ff04925c 100644 --- a/plugins/tokens/client/cli/atomic_swap.go +++ b/plugins/tokens/client/cli/atomic_swap.go @@ -86,14 +86,14 @@ func (c Commander) initiateHTLT(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to generate random number") } randomNumberHash = swap.CalculateRandomHash(randomNumber, timestamp) - fmt.Println(fmt.Sprintf("Random number: %s", hex.EncodeToString(randomNumber))) + fmt.Printf("Random number: %s\n", hex.EncodeToString(randomNumber)) } else { randomNumberHash, err = hex.DecodeString(randomNumberHashStr) if err != nil { return err } } - fmt.Println(fmt.Sprintf("Timestamp: %d\nRandom number hash: %s", timestamp, hex.EncodeToString(randomNumberHash))) + fmt.Printf("Timestamp: %d\nRandom number hash: %s\n", timestamp, hex.EncodeToString(randomNumberHash)) heightSpan := viper.GetInt64(flagHeightSpan) crossChain := viper.GetBool(flagCrossChain) // build message @@ -266,6 +266,9 @@ func (c Commander) querySwap(cmd *cobra.Command, args []string) error { } else { output, err = c.Cdc.MarshalJSON(atomicSwap) } + if err != nil { + return err + } fmt.Println(string(output)) return nil diff --git a/plugins/tokens/client/cli/issue.go b/plugins/tokens/client/cli/issue.go index 8ac929eee..bbd2a3139 100644 --- a/plugins/tokens/client/cli/issue.go +++ b/plugins/tokens/client/cli/issue.go @@ -29,7 +29,7 @@ func issueTokenCmd(cmdr Commander) *cobra.Command { cmd.Flags().StringP(flagSymbol, "s", "", "symbol of the new token") cmd.Flags().Int64P(flagTotalSupply, "n", 0, "total supply of the new token") cmd.Flags().Bool(flagMintable, false, "whether the token can be minted") - cmd.MarkFlagRequired(flagTotalSupply) + _ = cmd.MarkFlagRequired(flagTotalSupply) return cmd } @@ -42,7 +42,7 @@ func mintTokenCmd(cmdr Commander) *cobra.Command { cmd.Flags().StringP(flagSymbol, "s", "", "symbol of the token") cmd.Flags().Int64P(flagAmount, "n", 0, "amount to mint") - cmd.MarkFlagRequired(flagAmount) + _ = cmd.MarkFlagRequired(flagAmount) return cmd } diff --git a/plugins/tokens/client/cli/issue_mini.go b/plugins/tokens/client/cli/issue_mini.go index a71c1b6a6..76224c0ce 100644 --- a/plugins/tokens/client/cli/issue_mini.go +++ b/plugins/tokens/client/cli/issue_mini.go @@ -28,7 +28,7 @@ func issueMiniTokenCmd(cmdr Commander) *cobra.Command { cmd.Flags().Int64P(flagTotalSupply, "n", 0, "total supply of the new token") cmd.Flags().Bool(flagMintable, false, "whether the token can be minted") cmd.Flags().String(flagTokenUri, "", "uri of the token information") - cmd.MarkFlagRequired(flagTotalSupply) + _ = cmd.MarkFlagRequired(flagTotalSupply) return cmd } diff --git a/plugins/tokens/client/cli/issue_tiny.go b/plugins/tokens/client/cli/issue_tiny.go index 4a5d1201f..730d5298e 100644 --- a/plugins/tokens/client/cli/issue_tiny.go +++ b/plugins/tokens/client/cli/issue_tiny.go @@ -22,7 +22,7 @@ func issueTinyTokenCmd(cmdr Commander) *cobra.Command { cmd.Flags().Int64P(flagTotalSupply, "n", 0, "total supply of the new token") cmd.Flags().Bool(flagMintable, false, "whether the token can be minted") cmd.Flags().String(flagTokenUri, "", "uri of the token information") - cmd.MarkFlagRequired(flagTotalSupply) + _ = cmd.MarkFlagRequired(flagTotalSupply) return cmd } diff --git a/plugins/tokens/client/cli/multi_send.go b/plugins/tokens/client/cli/multi_send.go index 3254882fd..7a7d50725 100644 --- a/plugins/tokens/client/cli/multi_send.go +++ b/plugins/tokens/client/cli/multi_send.go @@ -53,7 +53,7 @@ func MultiSendCmd(cdc *wire.Codec) *cobra.Command { } txPath := viper.GetString(flagTransfersFile) - txBytes := make([]byte, 0) + var txBytes []byte if txPath != "" { txBytes, err = os.ReadFile(txPath) if err != nil { diff --git a/plugins/tokens/client/rest/getbalance.go b/plugins/tokens/client/rest/getbalance.go index d6a41fa76..631beae41 100644 --- a/plugins/tokens/client/rest/getbalance.go +++ b/plugins/tokens/client/rest/getbalance.go @@ -28,8 +28,7 @@ func BalanceReqHandler(cdc *wire.Codec, ctx context.CLIContext, tokens tokens.Ma throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) @@ -89,6 +88,6 @@ func BalanceReqHandler(cdc *wire.Codec, ctx context.CLIContext, tokens tokens.Ma return } - w.Write(output) + _, _ = w.Write(output) } } diff --git a/plugins/tokens/client/rest/getbalances.go b/plugins/tokens/client/rest/getbalances.go index 85c813adb..7b695bb8e 100644 --- a/plugins/tokens/client/rest/getbalances.go +++ b/plugins/tokens/client/rest/getbalances.go @@ -25,8 +25,7 @@ func BalancesReqHandler( throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } return func(w http.ResponseWriter, r *http.Request) { @@ -59,6 +58,6 @@ func BalancesReqHandler( w.Header().Set("Content-Type", responseType) w.WriteHeader(http.StatusOK) - w.Write(output) + _, _ = w.Write(output) } } diff --git a/plugins/tokens/client/rest/getswap.go b/plugins/tokens/client/rest/getswap.go index 5a635d23a..3b67b9581 100644 --- a/plugins/tokens/client/rest/getswap.go +++ b/plugins/tokens/client/rest/getswap.go @@ -20,8 +20,7 @@ func QuerySwapReqHandler( throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } return func(w http.ResponseWriter, r *http.Request) { @@ -58,6 +57,6 @@ func QuerySwapReqHandler( } w.Header().Set("Content-Type", responseType) w.WriteHeader(http.StatusOK) - w.Write(output) + _, _ = w.Write(output) } } diff --git a/plugins/tokens/client/rest/getswapsbycreator.go b/plugins/tokens/client/rest/getswapsbycreator.go index ea69efdd3..3d5a5ad2e 100644 --- a/plugins/tokens/client/rest/getswapsbycreator.go +++ b/plugins/tokens/client/rest/getswapsbycreator.go @@ -22,8 +22,7 @@ func QuerySwapIDsByCreatorReqHandler( throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } return func(w http.ResponseWriter, r *http.Request) { @@ -95,6 +94,6 @@ func QuerySwapIDsByCreatorReqHandler( } w.Header().Set("Content-Type", responseType) w.WriteHeader(http.StatusOK) - w.Write(output) + _, _ = w.Write(output) } } diff --git a/plugins/tokens/client/rest/getswapsbyrecipient.go b/plugins/tokens/client/rest/getswapsbyrecipient.go index 043454222..859c98382 100644 --- a/plugins/tokens/client/rest/getswapsbyrecipient.go +++ b/plugins/tokens/client/rest/getswapsbyrecipient.go @@ -22,8 +22,7 @@ func QuerySwapIDsByRecipientReqHandler( throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } return func(w http.ResponseWriter, r *http.Request) { @@ -93,6 +92,6 @@ func QuerySwapIDsByRecipientReqHandler( } w.Header().Set("Content-Type", responseType) w.WriteHeader(http.StatusOK) - w.Write(output) + _, _ = w.Write(output) } } diff --git a/plugins/tokens/client/rest/gettimelock.go b/plugins/tokens/client/rest/gettimelock.go index 84bf14e7f..ea9b5b74b 100644 --- a/plugins/tokens/client/rest/gettimelock.go +++ b/plugins/tokens/client/rest/gettimelock.go @@ -45,8 +45,7 @@ func GetTimeLockReqHandler(cdc *wire.Codec, ctx context.CLIContext) http.Handler throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } return func(w http.ResponseWriter, r *http.Request) { @@ -101,6 +100,6 @@ func GetTimeLockReqHandler(cdc *wire.Codec, ctx context.CLIContext) http.Handler w.Header().Set("Content-Type", responseType) w.WriteHeader(http.StatusOK) - w.Write(output) + _, _ = w.Write(output) } } diff --git a/plugins/tokens/client/rest/gettimelocks.go b/plugins/tokens/client/rest/gettimelocks.go index c81c5d975..a213277fc 100644 --- a/plugins/tokens/client/rest/gettimelocks.go +++ b/plugins/tokens/client/rest/gettimelocks.go @@ -44,8 +44,7 @@ func GetTimeLocksReqHandler(cdc *wire.Codec, ctx context.CLIContext) http.Handle throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } return func(w http.ResponseWriter, r *http.Request) { @@ -91,6 +90,6 @@ func GetTimeLocksReqHandler(cdc *wire.Codec, ctx context.CLIContext) http.Handle w.Header().Set("Content-Type", responseType) w.WriteHeader(http.StatusOK) - w.Write(output) + _, _ = w.Write(output) } } diff --git a/plugins/tokens/client/rest/gettoken.go b/plugins/tokens/client/rest/gettoken.go index 062edce06..0f83bcc51 100644 --- a/plugins/tokens/client/rest/gettoken.go +++ b/plugins/tokens/client/rest/gettoken.go @@ -46,8 +46,7 @@ func GetTokenReqHandler(cdc *wire.Codec, ctx context.CLIContext, isMini bool) ht throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } return func(w http.ResponseWriter, r *http.Request) { @@ -85,6 +84,6 @@ func GetTokenReqHandler(cdc *wire.Codec, ctx context.CLIContext, isMini bool) ht w.Header().Set("Content-Type", responseType) w.WriteHeader(http.StatusOK) - w.Write(output) + _, _ = w.Write(output) } } diff --git a/plugins/tokens/client/rest/gettokens.go b/plugins/tokens/client/rest/gettokens.go index eb453bb8f..03a3b502a 100644 --- a/plugins/tokens/client/rest/gettokens.go +++ b/plugins/tokens/client/rest/gettokens.go @@ -50,8 +50,7 @@ func GetTokensReqHandler(cdc *wire.Codec, ctx context.CLIContext, isMini bool) h throw := func(w http.ResponseWriter, status int, err error) { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(status) - w.Write([]byte(err.Error())) - return + _, _ = w.Write([]byte(err.Error())) } return func(w http.ResponseWriter, r *http.Request) { @@ -112,6 +111,6 @@ func GetTokensReqHandler(cdc *wire.Codec, ctx context.CLIContext, isMini bool) h w.Header().Set("Content-Type", responseType) w.WriteHeader(http.StatusOK) - w.Write(output) + _, _ = w.Write(output) } } diff --git a/plugins/tokens/client/rest/helpers.go b/plugins/tokens/client/rest/helpers.go index 693d14fbb..9c519c349 100644 --- a/plugins/tokens/client/rest/helpers.go +++ b/plugins/tokens/client/rest/helpers.go @@ -31,8 +31,7 @@ func GetBalances( // must do it this way because GetTokenList relies on store.Iterator // which we can't use from a CLIContext - var denoms map[string]bool - denoms = map[string]bool{} + denoms := map[string]bool{} for _, coin := range coins { denom := coin.Denom exists := tokens.ExistsCC(ctx, denom) @@ -41,10 +40,8 @@ func GetBalances( } } - symbs := make([]string, 0, len(denoms)) bals := make([]TokenBalance, 0, len(denoms)) for symb := range denoms { - symbs = append(symbs, symb) // count locked and frozen coins var locked, frozen int64 lockedc, err := getLockedCC(cdc, ctx, addr) diff --git a/plugins/tokens/freeze/handler.go b/plugins/tokens/freeze/handler.go index 2ba26329e..70a3fb952 100644 --- a/plugins/tokens/freeze/handler.go +++ b/plugins/tokens/freeze/handler.go @@ -52,7 +52,7 @@ func handleFreezeToken(ctx sdk.Context, tokenMapper store.Mapper, accKeeper auth newFrozenTokens := account.GetFrozenCoins().Plus(sdk.Coins{{Denom: symbol, Amount: freezeAmount}}) newFreeTokens := account.GetCoins().Minus(sdk.Coins{{Denom: symbol, Amount: freezeAmount}}) account.SetFrozenCoins(newFrozenTokens) - account.SetCoins(newFreeTokens) + _ = account.SetCoins(newFreeTokens) accKeeper.SetAccount(ctx, account) logger.Info("finish freezing token", "NewFrozenToken", newFrozenTokens, "NewFreeTokens", newFreeTokens) return sdk.Result{} @@ -81,7 +81,7 @@ func handleUnfreezeToken(ctx sdk.Context, tokenMapper store.Mapper, accKeeper au newFrozenTokens := account.GetFrozenCoins().Minus(sdk.Coins{{Denom: symbol, Amount: unfreezeAmount}}) newFreeTokens := account.GetCoins().Plus(sdk.Coins{{Denom: symbol, Amount: unfreezeAmount}}) account.SetFrozenCoins(newFrozenTokens) - account.SetCoins(newFreeTokens) + _ = account.SetCoins(newFreeTokens) accKeeper.SetAccount(ctx, account) logger.Debug("finish unfreezing token", "NewFrozenToken", newFrozenTokens, "NewFreeTokens", newFreeTokens) return sdk.Result{} diff --git a/plugins/tokens/issue/handler.go b/plugins/tokens/issue/handler.go index d20ec022b..db8fa3d04 100644 --- a/plugins/tokens/issue/handler.go +++ b/plugins/tokens/issue/handler.go @@ -105,7 +105,7 @@ func handleMintToken(ctx sdk.Context, tokenMapper store.Mapper, bankKeeper bank. err = tokenMapper.UpdateTotalSupply(ctx, symbol, newTotalSupply) if err != nil { logger.Error(errLogMsg, "reason", "update total supply failed: "+err.Error()) - return sdk.ErrInternal(fmt.Sprintf("update total supply failed")).Result() + return sdk.ErrInternal("update total supply failed").Result() } _, _, sdkError := bankKeeper.AddCoins(ctx, token.GetOwner(), diff --git a/plugins/tokens/issue/msg.go b/plugins/tokens/issue/msg.go index d63f573b7..8c1cb3d14 100644 --- a/plugins/tokens/issue/msg.go +++ b/plugins/tokens/issue/msg.go @@ -110,7 +110,7 @@ func (msg MintMsg) ValidateBasic() sdk.Error { } if msg.Symbol == types.NativeTokenSymbol { - return sdk.ErrInvalidCoins(fmt.Sprintf("cannot mint native token")) + return sdk.ErrInvalidCoins("cannot mint native token") } // handler will check: msg.Amount + token.TotalSupply <= types.MaxTotalSupply diff --git a/plugins/tokens/seturi/handler.go b/plugins/tokens/seturi/handler.go index 7a76a3af4..ba7ea975c 100644 --- a/plugins/tokens/seturi/handler.go +++ b/plugins/tokens/seturi/handler.go @@ -41,7 +41,7 @@ func handleSetURI(ctx sdk.Context, tokenMapper store.Mapper, msg SetURIMsg) sdk. } if len(msg.TokenURI) < 1 { - return sdk.ErrInvalidCoins(fmt.Sprintf("token uri should not be empty")).Result() + return sdk.ErrInvalidCoins("token uri should not be empty").Result() } if len(msg.TokenURI) > common.MaxTokenURILength { @@ -50,7 +50,7 @@ func handleSetURI(ctx sdk.Context, tokenMapper store.Mapper, msg SetURIMsg) sdk. err = tokenMapper.UpdateMiniTokenURI(ctx, symbol, msg.TokenURI) if err != nil { logger.Error(errLogMsg, "reason", "update token uri failed: "+err.Error()) - return sdk.ErrInternal(fmt.Sprintf("update token uri failed")).Result() + return sdk.ErrInternal("update token uri failed").Result() } logger.Info("finished update token uri") diff --git a/plugins/tokens/swap/handler.go b/plugins/tokens/swap/handler.go index 41cc39c1e..4c740500f 100644 --- a/plugins/tokens/swap/handler.go +++ b/plugins/tokens/swap/handler.go @@ -114,7 +114,7 @@ func handleClaimHashTimerLockedTransfer(ctx sdk.Context, kp Keeper, msg ClaimHTL } if !bytes.Equal(CalculateRandomHash(msg.RandomNumber, swap.Timestamp), swap.RandomNumberHash) { - return ErrMismatchedRandomNumber(fmt.Sprintf("Mismatched random number")).Result() + return ErrMismatchedRandomNumber("Mismatched random number").Result() } if !swap.CrossChain && swap.InAmount.IsZero() { diff --git a/plugins/tokens/timelock/msgs.go b/plugins/tokens/timelock/msgs.go index 08ee52878..472581485 100644 --- a/plugins/tokens/timelock/msgs.go +++ b/plugins/tokens/timelock/msgs.go @@ -147,7 +147,7 @@ func (msg TimeRelockMsg) ValidateBasic() sdk.Error { if len(msg.Description) == 0 && msg.Amount.IsZero() && msg.LockTime == 0 { - return ErrInvalidRelock(DefaultCodespace, fmt.Sprintf("nothing to update for time lock")) + return ErrInvalidRelock(DefaultCodespace, "nothing to update for time lock") } if sdk.IsUpgrade(sdk.BEP8) { From a322e282c9095de70784dc9098c47be466533f47 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Sun, 24 Apr 2022 15:21:22 +0800 Subject: [PATCH 36/43] change lint trigger condition --- .github/workflows/golangci-lint.yml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 16ea5fb0d..f6da933a2 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -2,11 +2,6 @@ name: golangci-lint on: push: - tags: - - v* - branches: - - master - - main pull_request: workflow_dispatch: jobs: From f321cece526cda0b5f68b939a797f9a5fff9ac3c Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Sun, 24 Apr 2022 15:34:00 +0800 Subject: [PATCH 37/43] update workflow --- .github/workflows/golangci-lint.yml | 5 ++--- .github/workflows/integration.yml | 5 +++-- Makefile | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index f6da933a2..db9bc3998 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -19,11 +19,10 @@ jobs: ~/go/bin ~/go/pkg/mod ~/.cache/go-build - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + key: lint-${{ hashFiles('**/go.sum') }} restore-keys: | - ${{ runner.os }}-go- + lint- - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" - run: go env -w GOPRIVATE="github.com/bnb-chain/*" - - run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.45.2 - name: golangci-lint run: make lint diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index c4c84d86a..4c889d940 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -18,11 +18,12 @@ jobs: - uses: actions/cache@v2 with: path: | + ~/go/bin ~/go/pkg/mod ~/.cache/go-build - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + key: integration-ci-${{ hashFiles('**/go.sum') }} restore-keys: | - ${{ runner.os }}-go- + integration-ci- - run: sudo apt-get update -y && sudo apt-get install -y expect - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" - run: go env -w GOPRIVATE="github.com/bnb-chain/*" diff --git a/Makefile b/Makefile index bb2a33c76..41778f321 100644 --- a/Makefile +++ b/Makefile @@ -145,7 +145,7 @@ format: ######################################## ### Lint install_lint: - which golangci-lint || curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.45.2 + which golangci-lint || go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.45.2 golangci-lint --version lint: install_lint From 65d08c4249662708e727d715cd8a906244db4f97 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Sun, 24 Apr 2022 15:43:36 +0800 Subject: [PATCH 38/43] optimize cache --- .github/workflows/golangci-lint.yml | 9 ++++++--- .github/workflows/integration.yml | 9 ++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index db9bc3998..f99a6f8f8 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -13,15 +13,18 @@ jobs: with: go-version: 1.16 - uses: actions/checkout@v3 + - uses: actions/cache@v2 + with: + path: ~/go/bin/golangci-lint + key: golangci-lint-1.45.2 - uses: actions/cache@v2 with: path: | - ~/go/bin ~/go/pkg/mod ~/.cache/go-build - key: lint-${{ hashFiles('**/go.sum') }} + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} restore-keys: | - lint- + ${{ runner.os }}-go- - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" - run: go env -w GOPRIVATE="github.com/bnb-chain/*" - name: golangci-lint diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 4c889d940..ad1f00d3e 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -15,15 +15,18 @@ jobs: go-version: 1.16 - name: Checkout uses: actions/checkout@v2 + - uses: actions/cache@v2 + with: + path: ~/go/bin + key: tools-v0 - uses: actions/cache@v2 with: path: | - ~/go/bin ~/go/pkg/mod ~/.cache/go-build - key: integration-ci-${{ hashFiles('**/go.sum') }} + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} restore-keys: | - integration-ci- + ${{ runner.os }}-go- - run: sudo apt-get update -y && sudo apt-get install -y expect - run: git config --global url."https://${{ secrets.GH_ACCESS_TOKEN }}@github.com".insteadOf "https://github.com" - run: go env -w GOPRIVATE="github.com/bnb-chain/*" From 9f1acb7bd6d920b257d032bf08005c7aebcfc7c6 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Sun, 24 Apr 2022 15:56:43 +0800 Subject: [PATCH 39/43] fix logger --- common/log/logger.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/common/log/logger.go b/common/log/logger.go index 78e11b65a..12cf27914 100644 --- a/common/log/logger.go +++ b/common/log/logger.go @@ -1,6 +1,7 @@ package log import ( + "fmt" "os" tmlog "github.com/tendermint/tendermint/libs/log" @@ -32,7 +33,7 @@ func NewAsyncFileLogger(filePath string, buffSize int64) tmlog.Logger { fileWriter = NewAsyncFileWriter(filePath, buffSize) err := fileWriter.Start() if err != nil { - panic(err) + fmt.Printf("Failed to start file writer in NewAsyncFileLogger: %v", err) } return tmlog.NewTMLogger(fileWriter) From ae977c8f3cac4c1805069825c2f2918521a77162 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Sun, 24 Apr 2022 16:06:33 +0800 Subject: [PATCH 40/43] fix test --- plugins/dex/order/keeper_recovery.go | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/plugins/dex/order/keeper_recovery.go b/plugins/dex/order/keeper_recovery.go index b899b89e3..7422d6e39 100644 --- a/plugins/dex/order/keeper_recovery.go +++ b/plugins/dex/order/keeper_recovery.go @@ -140,10 +140,7 @@ func (kp *DexKeeper) LoadOrderBookSnapshot(ctx sdk.Context, latestBlockHeight in if err != nil { panic(fmt.Sprintf("failed to unzip snapshort for orderbook [%s], err: %v", key, err)) } - _, err = io.Copy(&bw, r) - if err != nil { - panic(fmt.Sprintf("failed to unzip snapshort for orderbook [%s]: err: %v", key, err)) - } + _, _ = io.Copy(&bw, r) var ob OrderBookSnapshot err = kp.cdc.UnmarshalBinaryLengthPrefixed(bw.Bytes(), &ob) if err != nil { @@ -181,10 +178,7 @@ func (kp *DexKeeper) LoadOrderBookSnapshot(ctx sdk.Context, latestBlockHeight in if err != nil { panic(fmt.Sprintf("failed to unmarshal snapshort for active order [%s]", key)) } - _, err = io.Copy(&bw, r) - if err != nil { - panic(fmt.Sprintf("failed to unmarshal snapshort for active order [%s]: err: %v", key, err)) - } + _, _ = io.Copy(&bw, r) var ao ActiveOrders err = kp.cdc.UnmarshalBinaryLengthPrefixed(bw.Bytes(), &ao) if err != nil { From f5d2f5e972caeeab684ffa4995f8a2a617f5abd7 Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Sun, 24 Apr 2022 16:18:18 +0800 Subject: [PATCH 41/43] fix io.copy --- .golangci.yml | 2 +- networks/tools/snapshot_viewer/snapshot.go | 5 +---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 0cc0daa88..7730a1b7c 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -54,4 +54,4 @@ run: # Define the Go version limit. # Mainly related to generics support in go1.18. # Default: use Go version from the go.mod file, fallback on the env var `GOVERSION`, fallback on 1.17 -# go: '1.16' \ No newline at end of file +# go: '1.16' diff --git a/networks/tools/snapshot_viewer/snapshot.go b/networks/tools/snapshot_viewer/snapshot.go index 9b59891b0..7b26e71bf 100644 --- a/networks/tools/snapshot_viewer/snapshot.go +++ b/networks/tools/snapshot_viewer/snapshot.go @@ -149,10 +149,7 @@ func uncompress(bz []byte) []byte { panic(err) } defer r.Close() - _, err = io.Copy(&out, r) - if err != nil { - panic(err) - } + _, _ = io.Copy(&out, r) return out.Bytes() } From 997d3afe3302728f37b188531fb1484d4411227d Mon Sep 17 00:00:00 2001 From: zjubfd <296179868@qq.com> Date: Sun, 24 Apr 2022 20:44:25 +0800 Subject: [PATCH 42/43] fix precommit makefile --- Makefile | 4 ++-- app/pub/helpers.go | 21 ++++++++++++++++++--- plugins/dex/store/codec.go | 2 +- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 41778f321..16ec2c7e8 100644 --- a/Makefile +++ b/Makefile @@ -171,13 +171,13 @@ set_with_deadlock: cp go.sum go.sum_bak find . -name "*.go" | grep -v "vendor/" | xargs -n 1 sed -i.mutex_bak 's/sync.RWMutex/deadlock.RWMutex/' find . -name "*.go" | grep -v "vendor/" | xargs -n 1 sed -i.mutex_bak 's/sync.Mutex/deadlock.Mutex/' - find . -name "*.go" | grep -v "vendor/" | xargs -n 1 goimports -w + find . -name "*.go" | grep -v "vendor/" | grep -v ".git/" | xargs -n 1 goimports -w # cleanes up after you ran test_with_deadlock cleanup_after_test_with_deadlock: find . -name "*.go" | grep -v "vendor/" | xargs -n 1 sed -i.mutex_bak 's/deadlock.RWMutex/sync.RWMutex/' find . -name "*.go" | grep -v "vendor/" | xargs -n 1 sed -i.mutex_bak 's/deadlock.Mutex/sync.Mutex/' - find . -name "*.go" | grep -v "vendor/" | xargs -n 1 goimports -w + find . -name "*.go" | grep -v "vendor/" | grep -v ".git/" | xargs -n 1 goimports -w find . -name "*.go.mutex_bak" | grep -v "vendor/" | xargs rm mv go.mod_bak go.mod mv go.sum_bak go.sum diff --git a/app/pub/helpers.go b/app/pub/helpers.go index eac4679c8..8f93b9b62 100644 --- a/app/pub/helpers.go +++ b/app/pub/helpers.go @@ -281,9 +281,19 @@ func MatchAndAllocateAllForPublish(dexKeeper *orderPkg.DexKeeper, ctx sdk.Contex if tran.IsExpire() { if tran.IsExpiredWithFee() { // we only got expire of Ioc here, gte orders expire is handled in breathe block - iocExpireFeeHolderCh <- orderPkg.ExpireHolder{OrderId: tran.Oid, Reason: orderPkg.IocNoFill, Fee: tran.Fee.String(), Symbol: tran.Symbol} + iocExpireFeeHolderCh <- orderPkg.ExpireHolder{ + OrderId: tran.Oid, + Reason: orderPkg.IocNoFill, + Fee: tran.Fee.String(), + Symbol: tran.Symbol, + } } else { - iocExpireFeeHolderCh <- orderPkg.ExpireHolder{OrderId: tran.Oid, Reason: orderPkg.IocExpire, Fee: tran.Fee.String(), Symbol: tran.Symbol} + iocExpireFeeHolderCh <- orderPkg.ExpireHolder{ + OrderId: tran.Oid, + Reason: orderPkg.IocExpire, + Fee: tran.Fee.String(), + Symbol: tran.Symbol, + } } } } @@ -358,7 +368,12 @@ func DelistTradingPairForPublish(ctx sdk.Context, dexKeeper *orderPkg.DexKeeper, go updateExpireFeeForPublish(dexKeeper, &wg, expireHolderCh) var collectorForExpires = func(tran orderPkg.Transfer) { if tran.IsExpire() { - expireHolderCh <- orderPkg.ExpireHolder{OrderId: tran.Oid, Reason: orderPkg.Expired, Fee: tran.Fee.String(), Symbol: tran.Symbol} + expireHolderCh <- orderPkg.ExpireHolder{ + OrderId: tran.Oid, + Reason: orderPkg.Expired, + Fee: tran.Fee.String(), + Symbol: tran.Symbol, + } } } dexKeeper.DelistTradingPair(ctx, symbol, collectorForExpires) diff --git a/plugins/dex/store/codec.go b/plugins/dex/store/codec.go index 8ed22950b..5ac147cea 100644 --- a/plugins/dex/store/codec.go +++ b/plugins/dex/store/codec.go @@ -9,7 +9,7 @@ import ( ) // queryOrderBook queries the store for the serialized order book for a given pair. -func queryOrderBook(_cdc *wire.Codec, ctx context.CLIContext, pair string, levels int) (*[]byte, error) { +func queryOrderBook(_ *wire.Codec, ctx context.CLIContext, pair string, levels int) (*[]byte, error) { path := fmt.Sprintf("dex/orderbook/%s/%d", pair, levels) bz, err := ctx.Query(path, nil) if err != nil { From d76ea386837b4678d6aac800589611ea7e6cc99c Mon Sep 17 00:00:00 2001 From: Owen Hu Date: Mon, 25 Apr 2022 09:49:40 +0800 Subject: [PATCH 43/43] remove panic in engine --- plugins/dex/matcheng/engine.go | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/plugins/dex/matcheng/engine.go b/plugins/dex/matcheng/engine.go index bcf6e5b64..1eec6a40f 100644 --- a/plugins/dex/matcheng/engine.go +++ b/plugins/dex/matcheng/engine.go @@ -242,10 +242,7 @@ func (me *MatchEng) DropFilledOrder() (droppedIds []string) { me.Book.RemovePriceLevel(p.Price, BUYSIDE) } else { for i := toRemoveStartIdx; i < toRemoveEndIdx; i++ { - _, err := me.Book.RemoveOrder(droppedIds[i], BUYSIDE, p.Price) - if err != nil { - panic(err) - } + _, _ = me.Book.RemoveOrder(droppedIds[i], BUYSIDE, p.Price) } } } @@ -262,10 +259,8 @@ func (me *MatchEng) DropFilledOrder() (droppedIds []string) { me.Book.RemovePriceLevel(p.Price, SELLSIDE) } else { for i := toRemoveStartIdx; i < toRemoveEndIdx; i++ { - _, err := me.Book.RemoveOrder(droppedIds[i], SELLSIDE, p.Price) - if err != nil { - panic(err) - } + _, _ = me.Book.RemoveOrder(droppedIds[i], SELLSIDE, p.Price) + } } }