diff --git a/.github/workflows/lint-go.yaml b/.github/workflows/lint-go.yaml index 30eb70d7b..408e01ae5 100644 --- a/.github/workflows/lint-go.yaml +++ b/.github/workflows/lint-go.yaml @@ -24,7 +24,7 @@ jobs: with: version: v1.54 # use the default if on main branch, otherwise use the pull request config - args: --timeout=30m --config=${{ github.event_name == 'pull_request' && '.golangci.pull-request.yml' || '.golangci.yml' }} + args: --timeout=30m --config=.golangci.yml only-new-issues: true skip-cache: true skip-pkg-cache: true diff --git a/.github/workflows/test-docker-build.yaml b/.github/workflows/test-docker-build.yaml index b80be30d5..01f925a50 100644 --- a/.github/workflows/test-docker-build.yaml +++ b/.github/workflows/test-docker-build.yaml @@ -1,4 +1,4 @@ -name: Docker +name: Test Docker Buld on: push: diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index f66161be9..547f8fa98 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -1,4 +1,4 @@ -name: Test +name: Unit Tests on: [push, pull_request] diff --git a/.golangci.pull-request.yml b/.golangci.pull-request.yml deleted file mode 100644 index 6fcbb0ba2..000000000 --- a/.golangci.pull-request.yml +++ /dev/null @@ -1,20 +0,0 @@ -# Please refer to the official golangci-lint config documentation for more details: -# https://golangci-lint.run/usage/configuration/ -# https://github.com/golangci/golangci-lint/blob/master/.golangci.reference.yml - -linters: - enable-all: true - -run: - timeout: 10m - tests: false - -issues: - max-issues-per-linter: 1000 - exclude-rules: - - path: vm/contracts.go - text: 'SA1019: "golang.org/x/crypto/ripemd160" is deprecated: RIPEMD-160 is a legacy hash and should not be used for new applications.' - - path: vm/bn256/cloudflare/optate.go - linters: - - deadcode - - staticcheck diff --git a/.golangci.yml b/.golangci.yml index f1aa4ecfb..cb30087d8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,22 +1,45 @@ # Please refer to the official golangci-lint config documentation for more details: # https://golangci-lint.run/usage/configuration/ # https://github.com/golangci/golangci-lint/blob/master/.golangci.reference.yml +run: + timeout: 10m + tests: true + # default is true. Enables skipping of directories: + # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ + skip-dirs-use-default: true linters: - disable: + disable-all: true + enable: + - goimports + - gosimple + - govet + - ineffassign + - misspell + - unconvert + - typecheck - unused - - errcheck + - staticcheck + - bidichk + - durationcheck + - exportloopref + - whitespace -run: - timeout: 10m - tests: false + # - structcheck # lots of false positives + # - errcheck #lot of false positives + # - contextcheck + # - errchkjson # lots of false positives + # - errorlint # this check crashes + # - exhaustive # silly check + # - makezero # false positives + # - nilerr # several intentional + +linters-settings: + gofmt: + simplify: true issues: max-issues-per-linter: 1000 exclude-rules: - path: vm/contracts.go text: 'SA1019: "golang.org/x/crypto/ripemd160" is deprecated: RIPEMD-160 is a legacy hash and should not be used for new applications.' - - path: vm/bn256/cloudflare/optate.go - linters: - - deadcode - - staticcheck diff --git a/Makefile b/Makefile index 91b76c140..f4f5e2952 100644 --- a/Makefile +++ b/Makefile @@ -57,8 +57,5 @@ test-coverage:| go_version_check #@ Run the tests with coverage lint_command_check: @command -v golangci-lint || (echo "golangci-lint not found, please install it from https://golangci-lint.run/usage/install/" && exit 1) -lint: | go_version_check lint_command_check #@ Run 'golangci-lint' on new code changes - @golangci-lint run --new --config .golangci.pull-request.yml - -lint-all: | go_version_check lint_command_check #@ Run 'golangci-lint' on the entire codebase +lint: | go_version_check lint_command_check #@ Run 'golangci-lint' @golangci-lint run --config .golangci.yml diff --git a/abi/abi_test.go b/abi/abi_test.go index 4a90ccfb6..b9f921b91 100644 --- a/abi/abi_test.go +++ b/abi/abi_test.go @@ -81,6 +81,5 @@ func TestABI(t *testing.T) { assert.Nil(t, err) assert.Equal(t, value, d) - } } diff --git a/api/accounts/accounts.go b/api/accounts/accounts.go index 8c4d130d9..e4842c74d 100644 --- a/api/accounts/accounts.go +++ b/api/accounts/accounts.go @@ -355,5 +355,4 @@ func (a *Accounts) Mount(root *mux.Router, pathPrefix string) { sub.Path("/{address}/storage/{key}").Methods("GET").HandlerFunc(utils.WrapHandlerFunc(a.handleGetStorage)) sub.Path("").Methods("POST").HandlerFunc(utils.WrapHandlerFunc(a.handleCallContract)) sub.Path("/{address}").Methods("POST").HandlerFunc(utils.WrapHandlerFunc(a.handleCallContract)) - } diff --git a/api/accounts/accounts_test.go b/api/accounts/accounts_test.go index 98338c83d..9697501d9 100644 --- a/api/accounts/accounts_test.go +++ b/api/accounts/accounts_test.go @@ -8,7 +8,7 @@ package accounts_test import ( "bytes" "encoding/json" - "io/ioutil" + "io" "math/big" "net/http" "net/http/httptest" @@ -32,16 +32,16 @@ import ( "github.com/vechain/thor/v2/tx" ) -var sol = ` pragma solidity ^0.4.18; - contract Test { - uint8 value; - function add(uint8 a,uint8 b) public pure returns(uint8) { - return a+b; - } - function set(uint8 v) public { - value = v; - } - }` +// pragma solidity ^0.4.18; +// contract Test { +// uint8 value; +// function add(uint8 a,uint8 b) public pure returns(uint8) { +// return a+b; +// } +// function set(uint8 v) public { +// value = v; +// } +// } var abiJSON = `[ { @@ -111,32 +111,31 @@ func TestAccount(t *testing.T) { } func getAccount(t *testing.T) { - res, statusCode := httpGet(t, ts.URL+"/accounts/"+invalidAddr) + _, statusCode := httpGet(t, ts.URL+"/accounts/"+invalidAddr) assert.Equal(t, http.StatusBadRequest, statusCode, "bad address") - res, statusCode = httpGet(t, ts.URL+"/accounts/"+addr.String()+"?revision="+invalidNumberRevision) + _, statusCode = httpGet(t, ts.URL+"/accounts/"+addr.String()+"?revision="+invalidNumberRevision) assert.Equal(t, http.StatusBadRequest, statusCode, "bad revision") //revision is optional defaut `best` - res, statusCode = httpGet(t, ts.URL+"/accounts/"+addr.String()) + res, statusCode := httpGet(t, ts.URL+"/accounts/"+addr.String()) var acc accounts.Account if err := json.Unmarshal(res, &acc); err != nil { t.Fatal(err) } assert.Equal(t, math.HexOrDecimal256(*value), acc.Balance, "balance should be equal") assert.Equal(t, http.StatusOK, statusCode, "OK") - } func getCode(t *testing.T) { - res, statusCode := httpGet(t, ts.URL+"/accounts/"+invalidAddr+"/code") + _, statusCode := httpGet(t, ts.URL+"/accounts/"+invalidAddr+"/code") assert.Equal(t, http.StatusBadRequest, statusCode, "bad address") - res, statusCode = httpGet(t, ts.URL+"/accounts/"+contractAddr.String()+"/code?revision="+invalidNumberRevision) + _, statusCode = httpGet(t, ts.URL+"/accounts/"+contractAddr.String()+"/code?revision="+invalidNumberRevision) assert.Equal(t, http.StatusBadRequest, statusCode, "bad revision") //revision is optional defaut `best` - res, statusCode = httpGet(t, ts.URL+"/accounts/"+contractAddr.String()+"/code") + res, statusCode := httpGet(t, ts.URL+"/accounts/"+contractAddr.String()+"/code") var code map[string]string if err := json.Unmarshal(res, &code); err != nil { t.Fatal(err) @@ -150,17 +149,17 @@ func getCode(t *testing.T) { } func getStorage(t *testing.T) { - res, statusCode := httpGet(t, ts.URL+"/accounts/"+invalidAddr+"/storage/"+storageKey.String()) + _, statusCode := httpGet(t, ts.URL+"/accounts/"+invalidAddr+"/storage/"+storageKey.String()) assert.Equal(t, http.StatusBadRequest, statusCode, "bad address") - res, statusCode = httpGet(t, ts.URL+"/accounts/"+contractAddr.String()+"/storage/"+invalidBytes32) + _, statusCode = httpGet(t, ts.URL+"/accounts/"+contractAddr.String()+"/storage/"+invalidBytes32) assert.Equal(t, http.StatusBadRequest, statusCode, "bad storage key") - res, statusCode = httpGet(t, ts.URL+"/accounts/"+contractAddr.String()+"/storage/"+storageKey.String()+"?revision="+invalidNumberRevision) + _, statusCode = httpGet(t, ts.URL+"/accounts/"+contractAddr.String()+"/storage/"+storageKey.String()+"?revision="+invalidNumberRevision) assert.Equal(t, http.StatusBadRequest, statusCode, "bad revision") //revision is optional defaut `best` - res, statusCode = httpGet(t, ts.URL+"/accounts/"+contractAddr.String()+"/storage/"+storageKey.String()) + res, statusCode := httpGet(t, ts.URL+"/accounts/"+contractAddr.String()+"/storage/"+storageKey.String()) var value map[string]string if err := json.Unmarshal(res, &value); err != nil { t.Fatal(err) @@ -190,9 +189,9 @@ func initAccountServer(t *testing.T) { packTx(repo, stater, transaction, t) method := "set" - abi, err := ABI.New([]byte(abiJSON)) + abi, _ := ABI.New([]byte(abiJSON)) m, _ := abi.MethodByName(method) - input, err := m.EncodeInput(uint8(storageValue)) + input, err := m.EncodeInput(storageValue) if err != nil { t.Fatal(err) } @@ -252,7 +251,7 @@ func deployContractWithCall(t *testing.T) { Gas: 10000000, Data: "abc", } - res, statusCode := httpPost(t, ts.URL+"/accounts", badBody) + _, statusCode := httpPost(t, ts.URL+"/accounts", badBody) assert.Equal(t, http.StatusBadRequest, statusCode, "bad data") reqBody := &accounts.CallData{ @@ -260,33 +259,32 @@ func deployContractWithCall(t *testing.T) { Data: hexutil.Encode(bytecode), } - res, statusCode = httpPost(t, ts.URL+"/accounts?revision="+invalidNumberRevision, reqBody) + _, statusCode = httpPost(t, ts.URL+"/accounts?revision="+invalidNumberRevision, reqBody) assert.Equal(t, http.StatusBadRequest, statusCode, "bad revision") //revision is optional defaut `best` - res, statusCode = httpPost(t, ts.URL+"/accounts", reqBody) + res, _ := httpPost(t, ts.URL+"/accounts", reqBody) var output *accounts.CallResult if err := json.Unmarshal(res, &output); err != nil { t.Fatal(err) } assert.False(t, output.Reverted) - } func callContract(t *testing.T) { - res, statusCode := httpPost(t, ts.URL+"/accounts/"+invalidAddr, nil) + _, statusCode := httpPost(t, ts.URL+"/accounts/"+invalidAddr, nil) assert.Equal(t, http.StatusBadRequest, statusCode, "invalid address") badBody := &accounts.CallData{ Data: "input", } - res, statusCode = httpPost(t, ts.URL+"/accounts/"+contractAddr.String(), badBody) + _, statusCode = httpPost(t, ts.URL+"/accounts/"+contractAddr.String(), badBody) assert.Equal(t, http.StatusBadRequest, statusCode, "invalid input data") a := uint8(1) b := uint8(2) method := "add" - abi, err := ABI.New([]byte(abiJSON)) + abi, _ := ABI.New([]byte(abiJSON)) m, _ := abi.MethodByName(method) input, err := m.EncodeInput(a, b) if err != nil { @@ -295,7 +293,7 @@ func callContract(t *testing.T) { reqBody := &accounts.CallData{ Data: hexutil.Encode(input), } - res, statusCode = httpPost(t, ts.URL+"/accounts/"+contractAddr.String(), reqBody) + res, statusCode := httpPost(t, ts.URL+"/accounts/"+contractAddr.String(), reqBody) var output *accounts.CallResult if err = json.Unmarshal(res, &output); err != nil { t.Fatal(err) @@ -327,13 +325,13 @@ func batchCall(t *testing.T) { Value: nil, }}, } - res, statusCode := httpPost(t, ts.URL+"/accounts/*", badBody) + _, statusCode := httpPost(t, ts.URL+"/accounts/*", badBody) assert.Equal(t, http.StatusBadRequest, statusCode, "invalid data") a := uint8(1) b := uint8(2) method := "add" - abi, err := ABI.New([]byte(abiJSON)) + abi, _ := ABI.New([]byte(abiJSON)) m, _ := abi.MethodByName(method) input, err := m.EncodeInput(a, b) if err != nil { @@ -353,10 +351,10 @@ func batchCall(t *testing.T) { }}, } - res, statusCode = httpPost(t, ts.URL+"/accounts/*?revision="+invalidNumberRevision, badBody) + _, statusCode = httpPost(t, ts.URL+"/accounts/*?revision="+invalidNumberRevision, badBody) assert.Equal(t, http.StatusBadRequest, statusCode, "invalid revision") - res, statusCode = httpPost(t, ts.URL+"/accounts/*", reqBody) + res, statusCode := httpPost(t, ts.URL+"/accounts/*", reqBody) var results accounts.BatchCallResults if err = json.Unmarshal(res, &results); err != nil { t.Fatal(err) @@ -399,7 +397,7 @@ func httpPost(t *testing.T, url string, body interface{}) ([]byte, int) { if err != nil { t.Fatal(err) } - r, err := ioutil.ReadAll(res.Body) + r, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { t.Fatal(err) @@ -412,7 +410,7 @@ func httpGet(t *testing.T, url string) ([]byte, int) { if err != nil { t.Fatal(err) } - r, err := ioutil.ReadAll(res.Body) + r, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { t.Fatal(err) diff --git a/api/api.go b/api/api.go index 7ad18d45c..e59eb3462 100644 --- a/api/api.go +++ b/api/api.go @@ -44,7 +44,6 @@ func New( allowCustomTracer bool, forkConfig thor.ForkConfig, ) (http.HandlerFunc, func()) { - origins := strings.Split(strings.TrimSpace(allowedOrigins), ",") for i, o := range origins { origins[i] = strings.ToLower(strings.TrimSpace(o)) diff --git a/api/blocks/blocks_test.go b/api/blocks/blocks_test.go index 941fbb1b6..f7079bfb4 100644 --- a/api/blocks/blocks_test.go +++ b/api/blocks/blocks_test.go @@ -7,7 +7,7 @@ package blocks import ( "encoding/json" - "io/ioutil" + "io" "math/big" "net/http" "net/http/httptest" @@ -28,11 +28,6 @@ import ( "github.com/vechain/thor/v2/tx" ) -const ( - testAddress = "56e81f171bcc55a6ff8345e692c0f86e5b48e01a" - testPrivHex = "efa321f290811731036e5eccd373114e5186d9fe419081f5a607231279d5ef01" -) - var blk *block.Block var ts *httptest.Server @@ -43,13 +38,13 @@ func TestBlock(t *testing.T) { initBlockServer(t) defer ts.Close() //invalid block id - res, statusCode := httpGet(t, ts.URL+"/blocks/"+invalidBytes32) + _, statusCode := httpGet(t, ts.URL+"/blocks/"+invalidBytes32) assert.Equal(t, http.StatusBadRequest, statusCode) //invalid block number - res, statusCode = httpGet(t, ts.URL+"/blocks/"+invalidNumberRevision) + _, statusCode = httpGet(t, ts.URL+"/blocks/"+invalidNumberRevision) assert.Equal(t, http.StatusBadRequest, statusCode) - res, statusCode = httpGet(t, ts.URL+"/blocks/"+blk.Header().ID().String()) + res, statusCode := httpGet(t, ts.URL+"/blocks/"+blk.Header().ID().String()) rb := new(JSONCollapsedBlock) if err := json.Unmarshal(res, rb); err != nil { t.Fatal(err) @@ -70,7 +65,6 @@ func TestBlock(t *testing.T) { } checkBlock(t, blk, rb) assert.Equal(t, http.StatusOK, statusCode) - } func initBlockServer(t *testing.T) { @@ -145,7 +139,6 @@ func checkBlock(t *testing.T, expBl *block.Block, actBl *JSONCollapsedBlock) { for i, tx := range expBl.Transactions() { assert.Equal(t, tx.ID(), actBl.Transactions[i], "txid should be equal") } - } func httpGet(t *testing.T, url string) ([]byte, int) { @@ -153,7 +146,7 @@ func httpGet(t *testing.T, url string) ([]byte, int) { if err != nil { t.Fatal(err) } - r, err := ioutil.ReadAll(res.Body) + r, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { t.Fatal(err) diff --git a/api/debug/debug.go b/api/debug/debug.go index 073d94baf..9a7280e50 100644 --- a/api/debug/debug.go +++ b/api/debug/debug.go @@ -458,5 +458,4 @@ func (d *Debug) Mount(root *mux.Router, pathPrefix string) { sub.Path("/tracers").Methods(http.MethodPost).HandlerFunc(utils.WrapHandlerFunc(d.handleTraceClause)) sub.Path("/tracers/call").Methods(http.MethodPost).HandlerFunc(utils.WrapHandlerFunc(d.handleTraceCall)) sub.Path("/storage-range").Methods(http.MethodPost).HandlerFunc(utils.WrapHandlerFunc(d.handleDebugStorage)) - } diff --git a/api/events/types.go b/api/events/types.go index 790f9985d..0dce06aa4 100644 --- a/api/events/types.go +++ b/api/events/types.go @@ -112,21 +112,19 @@ func convertEventFilter(chain *chain.Chain, filter *EventFilter) (*logdb.EventFi Order: filter.Order, } if len(filter.CriteriaSet) > 0 { - criterias := make([]*logdb.EventCriteria, len(filter.CriteriaSet)) - for i, criteria := range filter.CriteriaSet { + f.CriteriaSet = make([]*logdb.EventCriteria, len(filter.CriteriaSet)) + for i, criterion := range filter.CriteriaSet { var topics [5]*thor.Bytes32 - topics[0] = criteria.Topic0 - topics[1] = criteria.Topic1 - topics[2] = criteria.Topic2 - topics[3] = criteria.Topic3 - topics[4] = criteria.Topic4 - criteria := &logdb.EventCriteria{ - Address: criteria.Address, + topics[0] = criterion.Topic0 + topics[1] = criterion.Topic1 + topics[2] = criterion.Topic2 + topics[3] = criterion.Topic3 + topics[4] = criterion.Topic4 + f.CriteriaSet[i] = &logdb.EventCriteria{ + Address: criterion.Address, Topics: topics, } - criterias[i] = criteria } - f.CriteriaSet = criterias } return f, nil } diff --git a/api/node/node_test.go b/api/node/node_test.go index 59ecb0de5..7952415a3 100644 --- a/api/node/node_test.go +++ b/api/node/node_test.go @@ -6,7 +6,7 @@ package node_test import ( "encoding/json" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -60,7 +60,7 @@ func httpGet(t *testing.T, url string) []byte { if err != nil { t.Fatal(err) } - r, err := ioutil.ReadAll(res.Body) + r, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { t.Fatal(err) diff --git a/api/transactions/transactions.go b/api/transactions/transactions.go index 1f658044a..dc9acda75 100644 --- a/api/transactions/transactions.go +++ b/api/transactions/transactions.go @@ -175,7 +175,6 @@ func (t *Transactions) handleGetTransactionByID(w http.ResponseWriter, req *http return err } return utils.WriteJSON(w, tx) - } func (t *Transactions) handleGetTransactionReceiptByID(w http.ResponseWriter, req *http.Request) error { diff --git a/api/transactions/transactions_test.go b/api/transactions/transactions_test.go index d727562c7..c11f4c1bb 100644 --- a/api/transactions/transactions_test.go +++ b/api/transactions/transactions_test.go @@ -8,7 +8,7 @@ package transactions_test import ( "bytes" "encoding/json" - "io/ioutil" + "io" "math/big" "net/http" "net/http/httptest" @@ -69,7 +69,7 @@ func getTxReceipt(t *testing.T) { if err := json.Unmarshal(r, &receipt); err != nil { t.Fatal(err) } - assert.Equal(t, uint64(receipt.GasUsed), transaction.Gas(), "gas should be equal") + assert.Equal(t, receipt.GasUsed, transaction.Gas(), "gas should be equal") } func senTx(t *testing.T) { @@ -111,7 +111,7 @@ func httpPost(t *testing.T, url string, obj interface{}) []byte { if err != nil { t.Fatal(err) } - r, err := ioutil.ReadAll(res.Body) + r, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { t.Fatal(err) @@ -172,7 +172,6 @@ func initTransactionServer(t *testing.T) { router := mux.NewRouter() transactions.New(repo, txpool.New(repo, stater, txpool.Options{Limit: 10000, LimitPerAccount: 16, MaxLifetime: 10 * time.Minute})).Mount(router, "/transactions") ts = httptest.NewServer(router) - } func checkTx(t *testing.T, expectedTx *tx.Transaction, actualTx *transactions.Transaction) { @@ -189,7 +188,6 @@ func checkTx(t *testing.T, expectedTx *tx.Transaction, actualTx *transactions.Tr assert.Equal(t, *c.Value(), big.Int(actualTx.Clauses[i].Value)) assert.Equal(t, c.To(), actualTx.Clauses[i].To) } - } func httpGet(t *testing.T, url string) []byte { @@ -197,7 +195,7 @@ func httpGet(t *testing.T, url string) []byte { if err != nil { t.Fatal(err) } - r, err := ioutil.ReadAll(res.Body) + r, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { t.Fatal(err) diff --git a/api/transactions/types.go b/api/transactions/types.go index cb2380694..7aa3f822e 100644 --- a/api/transactions/types.go +++ b/api/transactions/types.go @@ -207,7 +207,6 @@ func convertReceipt(txReceipt *tx.Receipt, header *block.Header, tx *tx.Transact event.Topics = make([]thor.Bytes32, len(txEvent.Topics)) copy(event.Topics, txEvent.Topics) otp.Events[j] = event - } for j, txTransfer := range output.Transfers { transfer := &Transfer{ diff --git a/bft/engine.go b/bft/engine.go index 59e25cd21..54718f67e 100644 --- a/bft/engine.go +++ b/bft/engine.go @@ -211,7 +211,6 @@ func (engine *BFTEngine) ShouldVote(parentID thor.Bytes32) (bool, error) { if !includes { return false, nil } - } } @@ -234,7 +233,7 @@ func (engine *BFTEngine) computeState(header *block.Header) (*bftState, error) { ) if entry := engine.caches.justifier.Remove(header.ParentID()); !isCheckPoint(header.Number()) && entry != nil { - js = interface{}(entry.Entry.Value).(*justifier) + js = (entry.Entry.Value).(*justifier) end = header.Number() } else { // create a new vote set if cache missed or new block is checkpoint diff --git a/block/gas_limit_test.go b/block/gas_limit_test.go index c01cb4749..5fde2c413 100644 --- a/block/gas_limit_test.go +++ b/block/gas_limit_test.go @@ -15,7 +15,6 @@ import ( ) func TestGasLimit_IsValid(t *testing.T) { - tests := []struct { gl uint64 parentGL uint64 @@ -35,7 +34,6 @@ func TestGasLimit_IsValid(t *testing.T) { } func TestGasLimit_Adjust(t *testing.T) { - tests := []struct { gl uint64 delta int64 diff --git a/chain/block_reader_test.go b/chain/block_reader_test.go index 2253179ce..7d4c306e3 100644 --- a/chain/block_reader_test.go +++ b/chain/block_reader_test.go @@ -44,7 +44,6 @@ func TestBlockReader(t *testing.T) { break } blks = append(blks, r...) - } assert.Equal(t, []*chain.ExtendedBlock{ diff --git a/chain/repository_test.go b/chain/repository_test.go index b83f0a7f1..08a23c037 100644 --- a/chain/repository_test.go +++ b/chain/repository_test.go @@ -83,7 +83,6 @@ func TestRepository(t *testing.T) { repo1.SetBestBlockID(b1.Header().ID()) repo2, _ := NewRepository(db, b0) for _, repo := range []*Repository{repo1, repo2} { - assert.Equal(t, b1.Header().ID(), repo.BestBlockSummary().Header.ID()) s, err := repo.GetBlockSummary(b1.Header().ID()) assert.Nil(t, err) diff --git a/cmd/thor/node/node.go b/cmd/thor/node/node.go index 169439dac..72f584d57 100644 --- a/cmd/thor/node/node.go +++ b/cmd/thor/node/node.go @@ -79,7 +79,6 @@ func New( skipLogs bool, forkConfig thor.ForkConfig, ) *Node { - return &Node{ packer: packer.New(repo, stater, master.Address(), master.Beneficiary, forkConfig), cons: consensus.New(repo, stater, forkConfig), diff --git a/cmd/thor/sync_logdb.go b/cmd/thor/sync_logdb.go index d8272bc5e..c27364ba2 100644 --- a/cmd/thor/sync_logdb.go +++ b/cmd/thor/sync_logdb.go @@ -272,8 +272,8 @@ func verifyLogDBPerBlock( block *block.Block, receipts tx.Receipts, eventLogs []*logdb.Event, - transferLogs []*logdb.Transfer) error { - + transferLogs []*logdb.Transfer, +) error { convertTopics := func(topics []thor.Bytes32) (r [5]*thor.Bytes32) { for i, t := range topics { t := t diff --git a/comm/communicator.go b/comm/communicator.go index 27fcb5883..574d53278 100644 --- a/comm/communicator.go +++ b/comm/communicator.go @@ -251,7 +251,6 @@ func (c *Communicator) BroadcastBlock(blk *block.Block) { peer := peer peer.MarkBlock(blk.Header().ID()) c.goes.Go(func() { - if err := proto.NotifyNewBlockID(c.ctx, peer, blk.Header().ID()); err != nil { peer.logger.Debug("failed to broadcast new block id", "err", err) } diff --git a/comm/handle_rpc.go b/comm/handle_rpc.go index da5b474ba..d7942a996 100644 --- a/comm/handle_rpc.go +++ b/comm/handle_rpc.go @@ -21,7 +21,6 @@ import ( // peer will be disconnected if error returned func (c *Communicator) handleRPC(peer *Peer, msg *p2p.Msg, write func(interface{}), txsToSync *txsToSync) (err error) { - log := peer.logger.New("msg", proto.MsgName(msg.Code)) log.Debug("received RPC call") defer func() { diff --git a/comm/txs_loop.go b/comm/txs_loop.go index 093c24492..85d887b35 100644 --- a/comm/txs_loop.go +++ b/comm/txs_loop.go @@ -11,7 +11,6 @@ import ( ) func (c *Communicator) txsLoop() { - txEvCh := make(chan *txpool.TxEvent, 10) sub := c.txPool.SubscribeTxEvent(txEvCh) defer sub.Unsubscribe() diff --git a/consensus/consensus_test.go b/consensus/consensus_test.go index 9f98a5ae1..4904b2656 100644 --- a/consensus/consensus_test.go +++ b/consensus/consensus_test.go @@ -90,7 +90,7 @@ func newTestConsensus() (*testConsensus, error) { proposer := genesis.DevAccounts()[0] p := packer.New(repo, stater, proposer.Address, &proposer.Address, forkConfig) parentSum, _ := repo.GetBlockSummary(parent.Header().ID()) - flow, err := p.Schedule(parentSum, uint64(parent.Header().Timestamp()+100*thor.BlockInterval)) + flow, err := p.Schedule(parentSum, parent.Header().Timestamp()+100*thor.BlockInterval) if err != nil { return nil, err } @@ -121,7 +121,7 @@ func newTestConsensus() (*testConsensus, error) { proposer2 := genesis.DevAccounts()[1] p2 := packer.New(repo, stater, proposer2.Address, &proposer2.Address, forkConfig) b1sum, _ := repo.GetBlockSummary(b1.Header().ID()) - flow2, err := p2.Schedule(b1sum, uint64(b1.Header().Timestamp()+100*thor.BlockInterval)) + flow2, err := p2.Schedule(b1sum, b1.Header().Timestamp()+100*thor.BlockInterval) if err != nil { return nil, err } @@ -229,7 +229,7 @@ func TestNewConsensus(t *testing.T) { } func TestNewRuntimeForReplay(t *testing.T) { - consensus, err := newTestConsensus() + consensus, _ := newTestConsensus() b1 := consensus.parent // Test for success scenario @@ -351,7 +351,6 @@ func TestValidateBlockHeader(t *testing.T) { assert.Equal(t, expected, err) assert.True(t, IsCritical(err)) assert.Equal(t, err.Error(), "block gas limit invalid: parent 10000000, current 20000000") - }, }, { diff --git a/consensus/errors.go b/consensus/errors.go index 11ac96176..2ae96e976 100644 --- a/consensus/errors.go +++ b/consensus/errors.go @@ -1,30 +1,30 @@ -// Copyright (c) 2018 The VeChainThor developers - -// Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying -// file LICENSE or - -package consensus - -import ( - "errors" -) - -var errFutureBlock = errors.New("block in the future") - -type consensusError string - -func (err consensusError) Error() string { - return string(err) -} - -// IsFutureBlock returns if the error indicates that the block should be -// processed later. -func IsFutureBlock(err error) bool { - return err == errFutureBlock -} - -// IsCritical returns if the error is consensus related. -func IsCritical(err error) bool { - _, ok := err.(consensusError) - return ok -} +// Copyright (c) 2018 The VeChainThor developers + +// Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying +// file LICENSE or + +package consensus + +import ( + "errors" +) + +var errFutureBlock = errors.New("block in the future") + +type consensusError string + +func (err consensusError) Error() string { + return string(err) +} + +// IsFutureBlock returns if the error indicates that the block should be +// processed later. +func IsFutureBlock(err error) bool { + return err == errFutureBlock +} + +// IsCritical returns if the error is consensus related. +func IsCritical(err error) bool { + _, ok := err.(consensusError) + return ok +} diff --git a/consensus/validator.go b/consensus/validator.go index f397e32b1..dc7ee85b3 100644 --- a/consensus/validator.go +++ b/consensus/validator.go @@ -62,7 +62,6 @@ func (c *Consensus) validate( // if no event emitted from Authority contract, it's believed that the candidates list not changed if !hasAuthorityEvent { - // if no endorsor related transfer, or no event emitted from Params contract, the proposers list // can be reused hasEndorsorEvent := func() bool { @@ -120,7 +119,7 @@ func (c *Consensus) validateBlockHeader(header *block.Header, parent *block.Head if header.Number() < c.forkConfig.VIP214 { if len(header.Alpha()) > 0 { - return consensusError("invlid block, alpha should be empty before VIP214") + return consensusError("invalid block, alpha should be empty before VIP214") } if len(signature) != 65 { return consensusError(fmt.Sprintf("block signature length invalid: want 65 have %v", len(signature))) diff --git a/genesis/customnet_test.go b/genesis/customnet_test.go index f5ff67664..f53a9cfec 100644 --- a/genesis/customnet_test.go +++ b/genesis/customnet_test.go @@ -58,7 +58,6 @@ func CustomNetWithParams(t *testing.T, executor genesis.Executor, baseGasPrice g } func TestNewCustomNet(t *testing.T) { - customGenesis := CustomNetWithParams(t, genesis.Executor{}, genesis.HexOrDecimal256{}, genesis.HexOrDecimal256{}, genesis.HexOrDecimal256{}) genesisBlock, err := genesis.NewCustomNet(&customGenesis) diff --git a/genesis/devnet.go b/genesis/devnet.go index 77798968e..5db8ad752 100644 --- a/genesis/devnet.go +++ b/genesis/devnet.go @@ -67,7 +67,6 @@ func NewDevnet() *Genesis { GasLimit(thor.InitialGasLimit). Timestamp(launchTime). State(func(state *state.State) error { - // setup builtin contracts if err := state.SetCode(builtin.Authority.Address, builtin.Authority.RuntimeBytecodes()); err != nil { return err diff --git a/logdb/logdb.go b/logdb/logdb.go index 985d9cd18..bcd793e94 100644 --- a/logdb/logdb.go +++ b/logdb/logdb.go @@ -95,7 +95,6 @@ func (db *LogDB) Path() string { } func (db *LogDB) FilterEvents(ctx context.Context, filter *EventFilter) ([]*Event, error) { - const query = `SELECT e.seq, r0.data, e.blockTime, r1.data, r2.data, e.clauseIndex, r3.data, r4.data, r5.data, r6.data, r7.data, r8.data, e.data FROM (%v) e LEFT JOIN ref r0 ON e.blockID = r0.id @@ -166,7 +165,6 @@ FROM (%v) e } func (db *LogDB) FilterTransfers(ctx context.Context, filter *TransferFilter) ([]*Transfer, error) { - const query = `SELECT t.seq, r0.data, t.blockTime, r1.data, r2.data, t.clauseIndex, r3.data, r4.data, t.amount FROM (%v) t LEFT JOIN ref r0 ON t.blockID = r0.id @@ -467,7 +465,6 @@ func (w *Writer) Write(b *block.Block, receipts tx.Receipts) error { tx := txs[i] txID = tx.ID() txOrigin, _ = tx.Origin() - } if err := w.exec( "INSERT OR IGNORE INTO ref(data) VALUES(?),(?)", diff --git a/logdb/logdb_test.go b/logdb/logdb_test.go index 87fbd8ea2..684c245cc 100644 --- a/logdb/logdb_test.go +++ b/logdb/logdb_test.go @@ -133,7 +133,6 @@ func TestEvents(t *testing.T) { var allTransfers transferLogs for i := 0; i < 100; i++ { - b = new(block.Builder). ParentID(b.Header().ID()). Transaction(newTx()). @@ -428,5 +427,4 @@ func TestLogDB_HasBlockID(t *testing.T) { t.Fatal(err) } assert.True(t, has) - } diff --git a/logdb/sequence_test.go b/logdb/sequence_test.go index d6bdf2395..24c7e47a2 100644 --- a/logdb/sequence_test.go +++ b/logdb/sequence_test.go @@ -1,7 +1,9 @@ package logdb -import "testing" -import "math" +import ( + "math" + "testing" +) func TestSequence(t *testing.T) { type args struct { diff --git a/logdb/types.go b/logdb/types.go index 5abd6572f..e4ebb1be4 100644 --- a/logdb/types.go +++ b/logdb/types.go @@ -88,7 +88,7 @@ type EventFilter struct { type TransferCriteria struct { TxOrigin *thor.Address //who send transaction Sender *thor.Address //who transferred tokens - Recipient *thor.Address //who recieved tokens + Recipient *thor.Address //who received tokens } func (c *TransferCriteria) toWhereCondition() (cond string, args []interface{}) { diff --git a/p2psrv/server.go b/p2psrv/server.go index f2f63d2e0..609516b41 100644 --- a/p2psrv/server.go +++ b/p2psrv/server.go @@ -202,7 +202,6 @@ func (s *Server) listenDiscV5() (err error) { } for _, node := range s.opts.KnownNodes { s.bootstrapNodes = append(s.bootstrapNodes, discv5.NewNode(discv5.NodeID(node.ID), node.IP, node.UDP, node.TCP)) - } if err := network.SetFallbackNodes(s.bootstrapNodes); err != nil { diff --git a/packer/flow_test.go b/packer/flow_test.go index 1c88f9833..d9baac228 100644 --- a/packer/flow_test.go +++ b/packer/flow_test.go @@ -112,7 +112,7 @@ func TestPack(t *testing.T) { proposer := genesis.DevAccounts()[0] p := packer.New(repo, stater, proposer.Address, &proposer.Address, forkConfig) parentSum, _ := repo.GetBlockSummary(parent.Header().ID()) - flow, _ := p.Schedule(parentSum, uint64(parent.Header().Timestamp()+100*thor.BlockInterval)) + flow, _ := p.Schedule(parentSum, parent.Header().Timestamp()+100*thor.BlockInterval) flow.Pack(proposer.PrivateKey, 0, false) diff --git a/packer/packer.go b/packer/packer.go index 3e2089145..aa85ade87 100644 --- a/packer/packer.go +++ b/packer/packer.go @@ -35,8 +35,8 @@ func New( stater *state.Stater, nodeMaster thor.Address, beneficiary *thor.Address, - forkConfig thor.ForkConfig) *Packer { - + forkConfig thor.ForkConfig, +) *Packer { return &Packer{ repo, stater, diff --git a/poa/candidates_test.go b/poa/candidates_test.go index b71ad26c0..16e43fd4e 100644 --- a/poa/candidates_test.go +++ b/poa/candidates_test.go @@ -17,7 +17,6 @@ import ( ) func generateCandidateList(candidateCount int) []*authority.Candidate { - candidateList := make([]*authority.Candidate, 0, candidateCount) for i := 0; i < candidateCount; i++ { var nodeMaster, endorsor thor.Address @@ -39,7 +38,6 @@ func generateCandidateList(candidateCount int) []*authority.Candidate { } func TestNewCandidates(t *testing.T) { - candidateList := generateCandidateList(5) // Call NewCandidates with the mock data @@ -124,7 +122,6 @@ func TestPick(t *testing.T) { } func TestUpdate(t *testing.T) { - candidateList := generateCandidateList(5) // Call NewCandidates with the mock data diff --git a/poa/sched.go b/poa/sched.go index cd2dcd6c1..446054c10 100644 --- a/poa/sched.go +++ b/poa/sched.go @@ -36,8 +36,8 @@ func NewSchedulerV1( addr thor.Address, proposers []Proposer, parentBlockNumber uint32, - parentBlockTime uint64) (*SchedulerV1, error) { - + parentBlockTime uint64, +) (*SchedulerV1, error) { actives := make([]Proposer, 0, len(proposers)) listed := false var proposer Proposer @@ -108,7 +108,6 @@ func (s *SchedulerV1) IsTheTime(newBlockTime uint64) bool { // Updates returns proposers whose status are changed, and the score when new block time is assumed to be newBlockTime. func (s *SchedulerV1) Updates(newBlockTime uint64) (updates []Proposer, score uint64) { - toDeactivate := make(map[thor.Address]Proposer) t := newBlockTime - thor.BlockInterval diff --git a/poa/sched_test.go b/poa/sched_test.go index 0fed063e9..8beb63891 100644 --- a/poa/sched_test.go +++ b/poa/sched_test.go @@ -34,7 +34,6 @@ var ( ) func TestSchedule(t *testing.T) { - _, err := poa.NewSchedulerV1(thor.BytesToAddress([]byte("px")), proposers, 1, parentTime) assert.NotNil(t, err) diff --git a/poa/sched_v2.go b/poa/sched_v2.go index 5cf3463e7..a0f204b69 100644 --- a/poa/sched_v2.go +++ b/poa/sched_v2.go @@ -33,7 +33,6 @@ func NewSchedulerV2( parentBlockNumber uint32, parentBlockTime uint64, seed []byte) (*SchedulerV2, error) { - var ( listed = false proposer Proposer diff --git a/poa/seed.go b/poa/seed.go index 4d340698e..ff738c57b 100644 --- a/poa/seed.go +++ b/poa/seed.go @@ -15,6 +15,8 @@ var epochInterval uint32 = thor.SeederInterval // mockEpochInterval mocks the epoch interval。 // TEST ONLY +// +//nolint:unused func mockEpochInterval(interval uint32) { epochInterval = interval } diff --git a/poa/seed_test.go b/poa/seed_test.go index 2d5192173..ce16d13e8 100644 --- a/poa/seed_test.go +++ b/poa/seed_test.go @@ -200,5 +200,4 @@ func TestSeeder_Generate(t *testing.T) { } }) } - } diff --git a/runtime/resolved_tx_test.go b/runtime/resolved_tx_test.go index 07c846b94..009cbcb3c 100644 --- a/runtime/resolved_tx_test.go +++ b/runtime/resolved_tx_test.go @@ -72,7 +72,6 @@ func (tr *testResolvedTransaction) currentState() *state.State { } func (tr *testResolvedTransaction) TestResolveTransaction() { - txBuild := func() *tx.Builder { return txBuilder(tr.repo.ChainTag()) } @@ -98,7 +97,6 @@ func (tr *testResolvedTransaction) TestResolveTransaction() { } func (tr *testResolvedTransaction) TestCommonTo() { - txBuild := func() *tx.Builder { return txBuilder(tr.repo.ChainTag()) } diff --git a/runtime/runtime.go b/runtime/runtime.go index 54055b5e2..fac4d3096 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -173,8 +173,8 @@ func (rt *Runtime) newEVM(stateDB *statedb.StateDB, clauseIndex uint32, txCtx *x panic(err) } - stateDB.SubBalance(common.Address(sender), amount) - stateDB.AddBalance(common.Address(recipient), amount) + stateDB.SubBalance(sender, amount) + stateDB.AddBalance(recipient, amount) stateDB.AddTransfer(&tx.Transfer{ Sender: thor.Address(sender), @@ -242,7 +242,7 @@ func (rt *Runtime) newEVM(stateDB *statedb.StateDB, clauseIndex uint32, txCtx *x } stateDB.AddLog(&types.Log{ - Address: common.Address(contractAddr), + Address: contractAddr, Topics: []common.Hash{common.Hash(prototypeSetMasterEvent.ID())}, Data: data, }) diff --git a/stackedmap/stackedmap_test.go b/stackedmap/stackedmap_test.go index b3b357efa..d9dbedec8 100644 --- a/stackedmap/stackedmap_test.go +++ b/stackedmap/stackedmap_test.go @@ -16,7 +16,6 @@ func M(a ...interface{}) []interface{} { return a } func TestStackedMap(t *testing.T) { - assert := assert.New(t) src := make(map[string]string) src["foo"] = "bar" diff --git a/state/cached_object.go b/state/cached_object.go index 1c0de092b..75f34d19a 100644 --- a/state/cached_object.go +++ b/state/cached_object.go @@ -54,7 +54,7 @@ func (co *cachedObject) getOrCreateStorageTrie() *muxdb.Trie { // GetStorage returns storage value for given key. func (co *cachedObject) GetStorage(key thor.Bytes32, steadyBlockNum uint32) (rlp.RawValue, error) { cache := &co.cache - // retrive from storage cache + // retrieve from storage cache if cache.storage != nil { if v, ok := cache.storage[key]; ok { return v, nil diff --git a/state/doc.go b/state/doc.go index 340c8e038..ec667b88b 100644 --- a/state/doc.go +++ b/state/doc.go @@ -6,18 +6,17 @@ // Package state manages the main accounts trie. // It follows the flow as bellow: // -// o -// | -// [ revertable state ] -// | -// [ stacked map ] -> [ journal ] -> [ playback(staging) ] -> [ updated trie ] -// | -// [ trie cache ] -// | -// [ read-only trie ] +// o +// | +// [ revert-able state ] +// | +// [ stacked map ] -> [ journal ] -> [ playback(staging) ] -> [ updated trie ] +// | +// [ trie cache ] +// | +// [ read-only trie ] // -// It's much simpler than Ethereum's statedb. -// An important difference with statedb is the logic of account suicide. +// It's much simpler than Ethereum's stateDB. +// An important difference with stateDB is the logic of account suicide. // TODO: explain more -// package state diff --git a/state/state.go b/state/state.go index 2dc251bf9..8fe7237c8 100644 --- a/state/state.go +++ b/state/state.go @@ -464,7 +464,7 @@ func (s *State) Stage(newBlockNum, newBlockConflicts uint32) (*Stage, error) { var enc lowrlp.Encoder enc.EncodeUint(uint64(newBlockNum)) enc.EncodeUint(uint64(newBlockConflicts)) - enc.EncodeUint(uint64(storageTrieCreationCount)) + enc.EncodeUint(storageTrieCreationCount) storageTrieCreationCount++ c.meta.StorageID = enc.ToBytes() } diff --git a/state/state_test.go b/state/state_test.go index baaf586db..94cf3f979 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -96,7 +96,6 @@ func TestStateRevert(t *testing.T) { assert.Equal(t, state.NewCheckpoint(), 1) state.RevertTo(0) assert.Equal(t, state.NewCheckpoint(), 0) - } func TestEnergy(t *testing.T) { @@ -142,9 +141,7 @@ func TestEncodeDecodeStorage(t *testing.T) { // Function to decode the storage value var decodedValue []byte decodeFunc := func(b []byte) error { - var err error - err = rlp.DecodeBytes(b, &decodedValue) - return err + return rlp.DecodeBytes(b, &decodedValue) } // Decode the stored value diff --git a/tracers/tracers_test.go b/tracers/tracers_test.go index 3913eefa8..bd44a85c0 100644 --- a/tracers/tracers_test.go +++ b/tracers/tracers_test.go @@ -236,7 +236,6 @@ func TestCallTracers(t *testing.T) { } assert.Equal(t, prestate(testData.State), pre) }) - } } @@ -266,7 +265,6 @@ func TestPreStateTracers(t *testing.T) { } assert.Equal(t, testData.diffState, got) }) - } } @@ -392,7 +390,7 @@ func TestInternals(t *testing.T) { rt.SetVMConfig(vm.Config{Tracer: tr}) gas := uint64(80000) - clause := tx.NewClause(&to).WithValue((*big.Int)(big.NewInt(0))) + clause := tx.NewClause(&to).WithValue(big.NewInt(0)) // to remain the same with testcases from ethereum, here deduct intrinsic gas since ethereum captures gas including intrinsic and we don't // we are capturing at clause level exec, _ := rt.PrepareClause(clause, 0, gas-21000, &xenv.TransactionContext{ diff --git a/trie/hasher.go b/trie/hasher.go index d8127a648..1b1bb384f 100644 --- a/trie/hasher.go +++ b/trie/hasher.go @@ -144,7 +144,6 @@ func (h *hasher) hashChildren(original node, db DatabaseWriter, path []byte) (no cached.Key = common.CopyBytes(n.Key) if _, ok := n.Val.(*valueNode); !ok { - collapsed.Val, cached.Val, err = h.hash(n.Val, db, append(path, n.Key...), false) if err != nil { return original, original, err diff --git a/trie/trie_test.go b/trie/trie_test.go index 006712753..22e49354d 100644 --- a/trie/trie_test.go +++ b/trie/trie_test.go @@ -20,7 +20,6 @@ import ( "bytes" "encoding/binary" "fmt" - "io/ioutil" "math/big" "math/rand" "os" @@ -52,7 +51,7 @@ func TestEmptyTrie(t *testing.T) { var trie Trie res := trie.Hash() exp := emptyRoot - if res != thor.Bytes32(exp) { + if res != exp { t.Errorf("expected %x got %x", exp, res) } } @@ -314,16 +313,6 @@ func TestLargeValue(t *testing.T) { trie.Hash() } -type countingDB struct { - Database - gets map[string]int -} - -func (db *countingDB) Get(key []byte) ([]byte, error) { - db.gets[string(key)]++ - return db.Database.Get(key) -} - // TestCacheUnload checks that decoded nodes are unloaded after a // certain number of commit operations. // func TestCacheUnload(t *testing.T) { @@ -587,7 +576,7 @@ func BenchmarkHash(b *testing.B) { } func tempDB() (string, Database) { - dir, err := ioutil.TempDir("", "trie-bench") + dir, err := os.MkdirTemp("", "trie-bench") if err != nil { panic(fmt.Sprintf("can't create temporary directory: %v", err)) } diff --git a/tx/receipt_test.go b/tx/receipt_test.go index 8b800ba08..6c1dc9f0f 100644 --- a/tx/receipt_test.go +++ b/tx/receipt_test.go @@ -36,7 +36,6 @@ func TestReceipt(t *testing.T) { } func TestReceiptStructure(t *testing.T) { - receipt := getMockReceipt() assert.Equal(t, uint64(1000), receipt.GasUsed) @@ -45,11 +44,9 @@ func TestReceiptStructure(t *testing.T) { assert.Equal(t, big.NewInt(50), receipt.Reward) assert.Equal(t, false, receipt.Reverted) assert.Equal(t, []*Output{}, receipt.Outputs) - } func TestEmptyRootHash(t *testing.T) { - receipt1 := getMockReceipt() receipt2 := getMockReceipt() diff --git a/tx/transaction.go b/tx/transaction.go index cada51765..3b0371da7 100644 --- a/tx/transaction.go +++ b/tx/transaction.go @@ -188,7 +188,7 @@ func (t *Transaction) Gas() uint64 { return t.body.Gas } -// Clauses returns caluses in tx. +// Clauses returns clauses in tx. func (t *Transaction) Clauses() []*Clause { return append([]*Clause(nil), t.body.Clauses...) } diff --git a/tx/transaction_test.go b/tx/transaction_test.go index 50b1f0b96..1a1f121d8 100644 --- a/tx/transaction_test.go +++ b/tx/transaction_test.go @@ -42,8 +42,7 @@ func TestIsExpired(t *testing.T) { func TestHash(t *testing.T) { tx := GetMockTx() res := tx.Hash() - assert.Equal(t, res, thor.Bytes32(thor.Bytes32{0x4b, 0xff, 0x70, 0x1, 0xfe, 0xc4, 0x2, 0x84, 0xd9, 0x3b, 0x4c, 0x45, 0x61, 0x7d, 0xc7, 0x41, 0xb9, 0xa8, 0x8e, 0xd5, 0x9d, 0xf, 0x1, 0xa3, 0x76, 0x39, 0x4c, 0x7b, 0xfe, 0xa6, 0xed, 0x24})) - + assert.Equal(t, res, thor.Bytes32{0x4b, 0xff, 0x70, 0x1, 0xfe, 0xc4, 0x2, 0x84, 0xd9, 0x3b, 0x4c, 0x45, 0x61, 0x7d, 0xc7, 0x41, 0xb9, 0xa8, 0x8e, 0xd5, 0x9d, 0xf, 0x1, 0xa3, 0x76, 0x39, 0x4c, 0x7b, 0xfe, 0xa6, 0xed, 0x24}) } func TestDependsOn(t *testing.T) { @@ -58,7 +57,6 @@ func TestTestFeatures(t *testing.T) { supportedFeatures := tx.Features(1) res := txx.TestFeatures(supportedFeatures) assert.Equal(t, res, nil) - } func TestToString(t *testing.T) { @@ -76,7 +74,6 @@ func TestToString(t *testing.T) { } func TestTxSize(t *testing.T) { - tx := GetMockTx() size := tx.Size() @@ -210,7 +207,6 @@ func TestTx(t *testing.T) { assert.Equal(t, "f8970184aabbccdd20f840df947567d83b7b8d80addcb281a71d54fc7b3364ffed82271086000000606060df947567d83b7b8d80addcb281a71d54fc7b3364ffed824e208600000060606081808252088083bc614ec0b841f76f3c91a834165872aa9464fc55b03a13f46ea8d3b858e528fcceaf371ad6884193c3f313ff8effbb57fe4d1adc13dceb933bedbf9dbb528d2936203d5511df00", func() string { d, _ := rlp.EncodeToBytes(trx); return hex.EncodeToString(d) }(), ) - } func TestDelegatedTx(t *testing.T) { diff --git a/txpool/blocklist_test.go b/txpool/blocklist_test.go index 0ae3ca705..8ff879bba 100644 --- a/txpool/blocklist_test.go +++ b/txpool/blocklist_test.go @@ -78,7 +78,7 @@ func TestSave(t *testing.T) { t.Errorf("Load failed: %s", err) } - fileContents, err := os.ReadFile(testFilePath) + fileContents, _ := os.ReadFile(testFilePath) str := string(fileContents) assert.True(t, strings.Contains(str, "0x25df024637d4e56c1ae9563987bf3e92c9f534c0")) assert.True(t, strings.Contains(str, "0x25df024637d4e56c1ae9563987bf3e92c9f534c1")) @@ -158,7 +158,6 @@ func TestFetch(t *testing.T) { t.Errorf("Fetch() missing address %s", addr) } } - }) } } diff --git a/txpool/tx_object_map_test.go b/txpool/tx_object_map_test.go index ae5c7dafa..52c4deb5a 100644 --- a/txpool/tx_object_map_test.go +++ b/txpool/tx_object_map_test.go @@ -111,7 +111,6 @@ func TestTxObjMap(t *testing.T) { assert.Equal(t, []*txObject{txObj3}, m.ToTxObjects()) assert.Equal(t, tx.Transactions{tx3}, m.ToTxs()) - } func TestLimitByDelegator(t *testing.T) { diff --git a/txpool/tx_object_test.go b/txpool/tx_object_test.go index 468e1a365..036e2c57a 100644 --- a/txpool/tx_object_test.go +++ b/txpool/tx_object_test.go @@ -136,7 +136,6 @@ func TestResolve(t *testing.T) { assert.Equal(t, tx, txObj.Transaction) assert.Equal(t, acc.Address, txObj.Origin()) - } func TestExecutable(t *testing.T) { diff --git a/txpool/tx_pool.go b/txpool/tx_pool.go index c8170b571..e4f8ce5c7 100644 --- a/txpool/tx_pool.go +++ b/txpool/tx_pool.go @@ -115,7 +115,6 @@ func (p *TxPool) housekeeping() { if headBlockChanged || poolLen > p.options.Limit || (poolLen < 200 && atomic.LoadUint32(&p.addedAfterWash) > 0) { - atomic.StoreUint32(&p.addedAfterWash, 0) startTime := mclock.Now() diff --git a/txpool/tx_pool_test.go b/txpool/tx_pool_test.go index 8913c06d8..b59ee0682 100644 --- a/txpool/tx_pool_test.go +++ b/txpool/tx_pool_test.go @@ -129,7 +129,6 @@ func TestAddWithFullErrorUnsyncedChain(t *testing.T) { defer pool.Close() FillPoolWithTxs(pool, t) - } func TestAddWithFullErrorSyncedChain(t *testing.T) { @@ -140,7 +139,6 @@ func TestAddWithFullErrorSyncedChain(t *testing.T) { } func TestNewCloseWithError(t *testing.T) { - pool := newPoolWithParams(LIMIT, LIMIT_PER_ACCOUNT, " ", " ", uint64(time.Now().Unix())+10000) defer pool.Close() diff --git a/vm/contracts_test.go b/vm/contracts_test.go index a254c3e86..973ea1c14 100644 --- a/vm/contracts_test.go +++ b/vm/contracts_test.go @@ -20,8 +20,8 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" "math/big" + "os" "testing" "time" @@ -184,7 +184,7 @@ func benchmarkPrecompiled(addr string, test precompiledTest, bench *testing.B) { return } if common.Bytes2Hex(res) != test.Expected { - bench.Error(fmt.Sprintf("Expected %v, got %v", test.Expected, common.Bytes2Hex(res))) + bench.Errorf("Expected %v, got %v", test.Expected, common.Bytes2Hex(res)) return } }) @@ -278,16 +278,6 @@ func testJson(name, addr string, t *testing.T) { } } -func testJsonFail(name, addr string, t *testing.T) { - tests, err := loadJsonFail(name) - if err != nil { - t.Fatal(err) - } - for _, test := range tests { - testPrecompiledFailure(addr, test, t) - } -} - func benchJson(name, addr string, b *testing.B) { tests, err := loadJson(name) if err != nil { @@ -299,7 +289,7 @@ func benchJson(name, addr string, b *testing.B) { } func loadJson(name string) ([]precompiledTest, error) { - data, err := ioutil.ReadFile(fmt.Sprintf("testdata/precompiles/%v.json", name)) + data, err := os.ReadFile(fmt.Sprintf("testdata/precompiles/%v.json", name)) if err != nil { return nil, err } @@ -307,13 +297,3 @@ func loadJson(name string) ([]precompiledTest, error) { err = json.Unmarshal(data, &testcases) return testcases, err } - -func loadJsonFail(name string) ([]precompiledFailureTest, error) { - data, err := ioutil.ReadFile(fmt.Sprintf("testdata/precompiles/fail-%v.json", name)) - if err != nil { - return nil, err - } - var testcases []precompiledFailureTest - err = json.Unmarshal(data, &testcases) - return testcases, err -} diff --git a/vm/gas_table.go b/vm/gas_table.go index 0d8c3d389..66aad61d9 100644 --- a/vm/gas_table.go +++ b/vm/gas_table.go @@ -25,7 +25,6 @@ import ( // memoryGasCosts calculates the quadratic gas for memory expansion. It does so // only for the memory region that is expanded, not the total memory. func memoryGasCost(mem *Memory, newMemSize uint64) (uint64, error) { - if newMemSize == 0 { return 0, nil } diff --git a/vm/instructions_test.go b/vm/instructions_test.go index e1d146828..4ce3ec91b 100644 --- a/vm/instructions_test.go +++ b/vm/instructions_test.go @@ -464,13 +464,12 @@ func TestCreate2Addreses(t *testing.T) { expected: "0xE33C0C7F7df4809055C3ebA6c09CFe4BaF1BD9e0", }, } { - origin := common.BytesToAddress(common.FromHex(tt.origin)) salt := common.BytesToHash(common.FromHex(tt.salt)) code := common.FromHex(tt.code) codeHash := thor.Keccak256(code).Bytes() // THOR: Cannot use crypto.CreateAddress2 function. - // v1.8.14 -> v1.8.27 depedency issue. See patch.go file. + // v1.8.14 -> v1.8.27 dependency issue. See patch.go file. address := CreateAddress2(origin, salt, codeHash) /* stack := newstack() @@ -485,6 +484,5 @@ func TestCreate2Addreses(t *testing.T) { if !bytes.Equal(expected.Bytes(), address.Bytes()) { t.Errorf("test %d: expected %s, got %s", i, expected.String(), address.String()) } - } } diff --git a/vrf/vrf_test.go b/vrf/vrf_test.go index d21b8691a..3dace6795 100644 --- a/vrf/vrf_test.go +++ b/vrf/vrf_test.go @@ -9,7 +9,7 @@ import ( "crypto/ecdsa" "encoding/hex" "encoding/json" - "io/ioutil" + "io" "os" "reflect" "testing" @@ -34,7 +34,7 @@ func readCases(fileName string) ([]Case, error) { } defer jsonFile.Close() - byteValue, err2 := ioutil.ReadAll(jsonFile) + byteValue, err2 := io.ReadAll(jsonFile) if err2 != nil { return nil, err2 } @@ -190,7 +190,6 @@ func Test_Secp256K1Sha256Tai_vrf_Verify_bad_message(t *testing.T) { return } }) - } func BenchmarkVRF(b *testing.B) {