From b8253e18adb112770ecdf6ad89e0133bd629a618 Mon Sep 17 00:00:00 2001 From: Pedro Gomes Date: Wed, 11 Sep 2024 08:46:59 +0100 Subject: [PATCH] Add revive linter (#838) * Update golangci-lint to update gosec * Adding Revive to linters * bft: update justifier.AddBlock * pr comments * pr comments --------- Co-authored-by: tony --- .golangci.yml | 11 ++ api/admin.go | 2 +- api/blocks/blocks_test.go | 12 +-- api/debug/debug.go | 4 +- api/debug/debug_test.go | 20 ++-- api/metrics.go | 8 +- api/node/node.go | 2 +- api/request_logger_test.go | 24 ++--- api/subscriptions/subscriptions.go | 4 +- api/subscriptions/types.go | 6 +- api/transactions/transactions_test.go | 20 ++-- api/utils/http_test.go | 14 +-- bft/casts.go | 2 +- bft/engine.go | 30 +++--- bft/engine_test.go | 41 +++---- bft/justifier.go | 4 +- block/block_test.go | 34 +++--- block/header_test.go | 4 +- chain/repository.go | 6 +- chain/repository_test.go | 16 +-- cmd/thor/main.go | 16 +-- cmd/thor/node/node.go | 16 +-- cmd/thor/node/stats_test.go | 4 +- cmd/thor/optimizer/optimizer_test.go | 6 +- genesis/customnet_test.go | 4 +- kv/bucket_test.go | 12 +-- log/handler.go | 18 ++-- logdb/logdb_bench_test.go | 4 +- metrics/noop.go | 2 +- muxdb/internal/trie/trie.go | 5 +- p2psrv/rpc/rpc.go | 2 +- p2psrv/server.go | 6 +- packer/packer_test.go | 4 +- poa/candidates.go | 10 +- runtime/statedb/statedb.go | 6 +- runtime/statedb/statedb_test.go | 4 +- stackedmap/stackedmap_test.go | 4 +- thor/bytes32_test.go | 4 +- thor/fork_config.go | 1 + tracers/js/goja.go | 28 ++--- tracers/js/tracer_test.go | 24 ++--- tracers/logger/logger.go | 28 ++--- tracers/logger/logger_json.go | 8 +- tracers/logger/logger_test.go | 12 +-- tracers/native/4byte.go | 6 +- tracers/native/call.go | 8 +- tracers/native/noop.go | 20 ++-- tracers/native/prestate.go | 8 +- trie/derive_root.go | 1 - trie/fast_node_encoder.go | 2 +- trie/node.go | 10 +- trie/trie_test.go | 2 +- tx/receipt_test.go | 16 +-- tx/transaction_test.go | 4 +- txpool/tx_pool_test.go | 4 +- vm/analysis.go | 2 +- vm/contracts.go | 10 +- vm/contracts_test.go | 36 +++---- vm/evm_test.go | 16 +-- vm/gas_table.go | 38 +++---- vm/gas_table_test.go | 2 +- vm/instructions.go | 150 +++++++++++++------------- vm/noop.go | 12 +-- vrf/vrf.go | 2 +- 64 files changed, 421 insertions(+), 420 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 76baf3bf4..7f12c1f02 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -25,6 +25,7 @@ linters: - copyloopvar - whitespace - gosec + - revive # - structcheck # lots of false positives # - errcheck #lot of false positives @@ -43,6 +44,16 @@ linters-settings: - G115 - G406 # ignore ripe160 deprecation - G507 # ignore ripe160 deprecation + revive: + rules: + - name: var-naming + severity: warning + disabled: false + exclude: [""] + arguments: + - [] # AllowList + - [] # DenyList + - - upperCaseConst: true # Extra parameter (upperCaseConst|skipPackageNameChecks) issues: max-issues-per-linter: 1000 diff --git a/api/admin.go b/api/admin.go index 06bf57cfe..50542ee8f 100644 --- a/api/admin.go +++ b/api/admin.go @@ -34,7 +34,7 @@ func writeError(w http.ResponseWriter, errCode int, errMsg string) { } func getLogLevelHandler(logLevel *slog.LevelVar) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, _ *http.Request) { response := logLevelResponse{ CurrentLevel: logLevel.Level().String(), } diff --git a/api/blocks/blocks_test.go b/api/blocks/blocks_test.go index d8ef60771..0ad5350b5 100644 --- a/api/blocks/blocks_test.go +++ b/api/blocks/blocks_test.go @@ -45,11 +45,11 @@ func TestBlock(t *testing.T) { for name, tt := range map[string]func(*testing.T){ "testBadQueryParams": testBadQueryParams, - "testInvalidBlockId": testInvalidBlockId, + "testInvalidBlockID": testInvalidBlockID, "testInvalidBlockNumber": testInvalidBlockNumber, - "testGetBlockById": testGetBlockById, + "testGetBlockByID": testGetBlockByID, "testGetBlockNotFound": testGetBlockNotFound, - "testGetExpandedBlockById": testGetExpandedBlockById, + "testGetExpandedBlockByID": testGetExpandedBlockByID, "testGetBlockByHeight": testGetBlockByHeight, "testGetBestBlock": testGetBestBlock, "testGetFinalizedBlock": testGetFinalizedBlock, @@ -111,7 +111,7 @@ func testGetJustifiedBlock(t *testing.T) { assert.Equal(t, genesisBlock.Header().ID(), justified.ID) } -func testGetBlockById(t *testing.T) { +func testGetBlockByID(t *testing.T) { res, statusCode := httpGet(t, ts.URL+"/blocks/"+blk.Header().ID().String()) rb := new(blocks.JSONCollapsedBlock) if err := json.Unmarshal(res, rb); err != nil { @@ -128,7 +128,7 @@ func testGetBlockNotFound(t *testing.T) { assert.Equal(t, "null", strings.TrimSpace(string(res))) } -func testGetExpandedBlockById(t *testing.T) { +func testGetExpandedBlockByID(t *testing.T) { res, statusCode := httpGet(t, ts.URL+"/blocks/"+blk.Header().ID().String()+"?expanded=true") rb := new(blocks.JSONExpandedBlock) if err := json.Unmarshal(res, rb); err != nil { @@ -144,7 +144,7 @@ func testInvalidBlockNumber(t *testing.T) { assert.Equal(t, http.StatusBadRequest, statusCode) } -func testInvalidBlockId(t *testing.T) { +func testInvalidBlockID(t *testing.T) { _, statusCode := httpGet(t, ts.URL+"/blocks/"+invalidBytes32) assert.Equal(t, http.StatusBadRequest, statusCode) } diff --git a/api/debug/debug.go b/api/debug/debug.go index 81543b109..e84a88d57 100644 --- a/api/debug/debug.go +++ b/api/debug/debug.go @@ -56,8 +56,8 @@ func New( allowCustomTracer bool, bft bft.Committer, allowedTracers []string, - soloMode bool) *Debug { - + soloMode bool, +) *Debug { allowedMap := make(map[string]struct{}) for _, t := range allowedTracers { allowedMap[t] = struct{}{} diff --git a/api/debug/debug_test.go b/api/debug/debug_test.go index 60a2821a0..3c61dfcab 100644 --- a/api/debug/debug_test.go +++ b/api/debug/debug_test.go @@ -54,9 +54,9 @@ func TestDebug(t *testing.T) { for name, tt := range map[string]func(*testing.T){ "testTraceClauseWithInvalidTracerName": testTraceClauseWithInvalidTracerName, "testTraceClauseWithEmptyTracerTarget": testTraceClauseWithEmptyTracerTarget, - "testTraceClauseWithBadBlockId": testTraceClauseWithBadBlockId, - "testTraceClauseWithNonExistingBlockId": testTraceClauseWithNonExistingBlockId, - "testTraceClauseWithBadTxId": testTraceClauseWithBadTxId, + "testTraceClauseWithBadBlockID": testTraceClauseWithBadBlockID, + "testTraceClauseWithNonExistingBlockID": testTraceClauseWithNonExistingBlockID, + "testTraceClauseWithBadTxID": testTraceClauseWithBadTxID, "testTraceClauseWithNonExistingTx": testTraceClauseWithNonExistingTx, "testTraceClauseWithBadClauseIndex": testTraceClauseWithBadClauseIndex, "testTraceClauseWithTxIndexOutOfBound": testTraceClauseWithTxIndexOutOfBound, @@ -74,7 +74,7 @@ func TestDebug(t *testing.T) { "testHandleTraceCall": testHandleTraceCall, "testHandleTraceCallWithValidRevisions": testHandleTraceCallWithValidRevisions, "testHandleTraceCallWithRevisionAsNonExistingHeight": testHandleTraceCallWithRevisionAsNonExistingHeight, - "testHandleTraceCallWithRevisionAsNonExistingId": testHandleTraceCallWithRevisionAsNonExistingId, + "testHandleTraceCallWithRevisionAsNonExistingID": testHandleTraceCallWithRevisionAsNonExistingID, "testHandleTraceCallWithMalfomredRevision": testHandleTraceCallWithMalfomredRevision, "testHandleTraceCallWithInsufficientGas": testHandleTraceCallWithInsufficientGas, "testHandleTraceCallWithBadBlockRef": testHandleTraceCallWithBadBlockRef, @@ -167,7 +167,7 @@ func testTraceClauseWithEmptyTracerTarget(t *testing.T) { assert.Equal(t, "target: unsupported", strings.TrimSpace(res)) } -func testTraceClauseWithBadBlockId(t *testing.T) { +func testTraceClauseWithBadBlockID(t *testing.T) { traceClauseOption := &TraceClauseOption{ Name: "structLogger", Target: "badBlockId/x/x", @@ -176,13 +176,13 @@ func testTraceClauseWithBadBlockId(t *testing.T) { assert.Equal(t, "target[0]: invalid length", strings.TrimSpace(res)) } -func testTraceClauseWithNonExistingBlockId(t *testing.T) { +func testTraceClauseWithNonExistingBlockID(t *testing.T) { _, _, _, err := debug.prepareClauseEnv(context.Background(), datagen.RandomHash(), 1, 1) assert.Error(t, err) } -func testTraceClauseWithBadTxId(t *testing.T) { +func testTraceClauseWithBadTxID(t *testing.T) { traceClauseOption := &TraceClauseOption{ Name: "structLogger", Target: fmt.Sprintf("%s/badTxId/x", blk.Header().ID()), @@ -192,10 +192,10 @@ func testTraceClauseWithBadTxId(t *testing.T) { } func testTraceClauseWithNonExistingTx(t *testing.T) { - nonExistingTxId := "0x4500ade0d72115abfc77571aef752df45ba5e87ca81fbd67fbfc46d455b17f91" + nonExistingTxID := "0x4500ade0d72115abfc77571aef752df45ba5e87ca81fbd67fbfc46d455b17f91" traceClauseOption := &TraceClauseOption{ Name: "structLogger", - Target: fmt.Sprintf("%s/%s/x", blk.Header().ID(), nonExistingTxId), + Target: fmt.Sprintf("%s/%s/x", blk.Header().ID(), nonExistingTxID), } res := httpPostAndCheckResponseStatus(t, ts.URL+"/debug/tracers", traceClauseOption, 403) assert.Equal(t, "transaction not found", strings.TrimSpace(res)) @@ -380,7 +380,7 @@ func testHandleTraceCallWithRevisionAsNonExistingHeight(t *testing.T) { assert.Equal(t, "revision: not found", strings.TrimSpace(res)) } -func testHandleTraceCallWithRevisionAsNonExistingId(t *testing.T) { +func testHandleTraceCallWithRevisionAsNonExistingID(t *testing.T) { nonExistingRevision := "0x4500ade0d72115abfc77571aef752df45ba5e87ca81fbd67fbfc46d455b17f91" res := httpPostAndCheckResponseStatus(t, ts.URL+"/debug/tracers/call?revision="+nonExistingRevision, &TraceCallOption{}, 400) diff --git a/api/metrics.go b/api/metrics.go index f0f29d8be..9fd5c3d94 100644 --- a/api/metrics.go +++ b/api/metrics.go @@ -19,8 +19,8 @@ import ( ) var ( - metricHttpReqCounter = metrics.LazyLoadCounterVec("api_request_count", []string{"name", "code", "method"}) - metricHttpReqDuration = metrics.LazyLoadHistogramVec("api_duration_ms", []string{"name", "code", "method"}, metrics.BucketHTTPReqs) + metricHTTPReqCounter = metrics.LazyLoadCounterVec("api_request_count", []string{"name", "code", "method"}) + metricHTTPReqDuration = metrics.LazyLoadHistogramVec("api_duration_ms", []string{"name", "code", "method"}, metrics.BucketHTTPReqs) metricActiveWebsocketCount = metrics.LazyLoadGaugeVec("api_active_websocket_count", []string{"subject"}) ) @@ -89,8 +89,8 @@ func metricsMiddleware(next http.Handler) http.Handler { if subscription != "" { metricActiveWebsocketCount().AddWithLabel(-1, map[string]string{"subject": subscription}) } else if enabled { - metricHttpReqCounter().AddWithLabel(1, map[string]string{"name": name, "code": strconv.Itoa(mrw.statusCode), "method": r.Method}) - metricHttpReqDuration().ObserveWithLabels(time.Since(now).Milliseconds(), map[string]string{"name": name, "code": strconv.Itoa(mrw.statusCode), "method": r.Method}) + metricHTTPReqCounter().AddWithLabel(1, map[string]string{"name": name, "code": strconv.Itoa(mrw.statusCode), "method": r.Method}) + metricHTTPReqDuration().ObserveWithLabels(time.Since(now).Milliseconds(), map[string]string{"name": name, "code": strconv.Itoa(mrw.statusCode), "method": r.Method}) } }) } diff --git a/api/node/node.go b/api/node/node.go index fa72fbedc..11c1ce7e1 100644 --- a/api/node/node.go +++ b/api/node/node.go @@ -26,7 +26,7 @@ func (n *Node) PeersStats() []*PeerStats { return ConvertPeersStats(n.nw.PeersStats()) } -func (n *Node) handleNetwork(w http.ResponseWriter, req *http.Request) error { +func (n *Node) handleNetwork(w http.ResponseWriter, _ *http.Request) error { return utils.WriteJSON(w, n.PeersStats()) } diff --git a/api/request_logger_test.go b/api/request_logger_test.go index 91e46ff66..6b8ddcd91 100644 --- a/api/request_logger_test.go +++ b/api/request_logger_test.go @@ -21,35 +21,35 @@ type mockLogger struct { loggedData []interface{} } -func (m *mockLogger) With(ctx ...interface{}) log.Logger { +func (m *mockLogger) With(_ ...interface{}) log.Logger { return m } -func (m *mockLogger) Log(level slog.Level, msg string, ctx ...interface{}) {} +func (m *mockLogger) Log(_ slog.Level, _ string, _ ...interface{}) {} -func (m *mockLogger) Trace(msg string, ctx ...interface{}) {} +func (m *mockLogger) Trace(_ string, _ ...interface{}) {} -func (m *mockLogger) Write(level slog.Level, msg string, attrs ...any) {} +func (m *mockLogger) Write(_ slog.Level, _ string, _ ...any) {} -func (m *mockLogger) Enabled(ctx context.Context, level slog.Level) bool { +func (m *mockLogger) Enabled(_ context.Context, _ slog.Level) bool { return true } func (m *mockLogger) Handler() slog.Handler { return nil } -func (m *mockLogger) New(ctx ...interface{}) log.Logger { return m } +func (m *mockLogger) New(_ ...interface{}) log.Logger { return m } -func (m *mockLogger) Debug(msg string, ctx ...interface{}) {} +func (m *mockLogger) Debug(_ string, _ ...interface{}) {} -func (m *mockLogger) Error(msg string, ctx ...interface{}) {} +func (m *mockLogger) Error(_ string, _ ...interface{}) {} -func (m *mockLogger) Crit(msg string, ctx ...interface{}) {} +func (m *mockLogger) Crit(_ string, _ ...interface{}) {} -func (m *mockLogger) Info(msg string, ctx ...interface{}) { +func (m *mockLogger) Info(_ string, ctx ...interface{}) { m.loggedData = append(m.loggedData, ctx...) } -func (m *mockLogger) Warn(msg string, ctx ...interface{}) { +func (m *mockLogger) Warn(_ string, ctx ...interface{}) { m.loggedData = append(m.loggedData, ctx...) } @@ -61,7 +61,7 @@ func TestRequestLoggerHandler(t *testing.T) { mockLog := &mockLogger{} // Define a test handler to wrap - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + testHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) }) diff --git a/api/subscriptions/subscriptions.go b/api/subscriptions/subscriptions.go index 0df6cd95b..73f895bf3 100644 --- a/api/subscriptions/subscriptions.go +++ b/api/subscriptions/subscriptions.go @@ -80,7 +80,7 @@ func New(repo *chain.Repository, allowedOrigins []string, backtraceLimit uint32, return sub } -func (s *Subscriptions) handleBlockReader(w http.ResponseWriter, req *http.Request) (*blockReader, error) { +func (s *Subscriptions) handleBlockReader(_ http.ResponseWriter, req *http.Request) (*blockReader, error) { position, err := s.parsePosition(req.URL.Query().Get("pos")) if err != nil { return nil, err @@ -128,7 +128,7 @@ func (s *Subscriptions) handleEventReader(w http.ResponseWriter, req *http.Reque return newEventReader(s.repo, position, eventFilter), nil } -func (s *Subscriptions) handleTransferReader(w http.ResponseWriter, req *http.Request) (*transferReader, error) { +func (s *Subscriptions) handleTransferReader(_ http.ResponseWriter, req *http.Request) (*transferReader, error) { position, err := s.parsePosition(req.URL.Query().Get("pos")) if err != nil { return nil, err diff --git a/api/subscriptions/types.go b/api/subscriptions/types.go index 8c58f4a19..76b3dc94c 100644 --- a/api/subscriptions/types.go +++ b/api/subscriptions/types.go @@ -43,9 +43,9 @@ func convertBlock(b *chain.ExtendedBlock) (*BlockMessage, error) { } txs := b.Transactions() - txIds := make([]thor.Bytes32, len(txs)) + txIDs := make([]thor.Bytes32, len(txs)) for i, tx := range txs { - txIds[i] = tx.ID() + txIDs[i] = tx.ID() } return &BlockMessage{ Number: header.Number(), @@ -63,7 +63,7 @@ func convertBlock(b *chain.ExtendedBlock) (*BlockMessage, error) { TxsRoot: header.TxsRoot(), TxsFeatures: uint32(header.TxsFeatures()), COM: header.COM(), - Transactions: txIds, + Transactions: txIDs, Obsolete: b.Obsolete, }, nil } diff --git a/api/transactions/transactions_test.go b/api/transactions/transactions_test.go index 52b127a56..2d86d13e3 100644 --- a/api/transactions/transactions_test.go +++ b/api/transactions/transactions_test.go @@ -54,7 +54,7 @@ func TestTransaction(t *testing.T) { // Get tx for name, tt := range map[string]func(*testing.T){ "getTx": getTx, - "getTxWithBadId": getTxWithBadId, + "getTxWithBadID": getTxWithBadID, "txWithBadHeader": txWithBadHeader, "getNonExistingRawTransactionWhenTxStillInMempool": getNonExistingRawTransactionWhenTxStillInMempool, "getNonPendingRawTransactionWhenTxStillInMempool": getNonPendingRawTransactionWhenTxStillInMempool, @@ -70,7 +70,7 @@ func TestTransaction(t *testing.T) { // Get tx receipt for name, tt := range map[string]func(*testing.T){ "getTxReceipt": getTxReceipt, - "getReceiptWithBadId": getReceiptWithBadId, + "getReceiptWithBadID": getReceiptWithBadID, "handleGetTransactionReceiptByIDWithNonExistingHead": handleGetTransactionReceiptByIDWithNonExistingHead, } { t.Run(name, tt) @@ -136,10 +136,10 @@ func sendTx(t *testing.T) { assert.Equal(t, tx.ID().String(), txObj["id"], "should be the same transaction id") } -func getTxWithBadId(t *testing.T) { - txBadId := "0x123" +func getTxWithBadID(t *testing.T) { + txBadID := "0x123" - res := httpGetAndCheckResponseStatus(t, ts.URL+"/transactions/"+txBadId, 400) + res := httpGetAndCheckResponseStatus(t, ts.URL+"/transactions/"+txBadID, 400) assert.Contains(t, string(res), "invalid length") } @@ -156,21 +156,21 @@ func txWithBadHeader(t *testing.T) { } } -func getReceiptWithBadId(t *testing.T) { - txBadId := "0x123" +func getReceiptWithBadID(t *testing.T) { + txBadID := "0x123" - httpGetAndCheckResponseStatus(t, ts.URL+"/transactions/"+txBadId+"/receipt", 400) + httpGetAndCheckResponseStatus(t, ts.URL+"/transactions/"+txBadID+"/receipt", 400) } func getNonExistingRawTransactionWhenTxStillInMempool(t *testing.T) { - nonExistingTxId := "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + nonExistingTxID := "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" queryParams := []string{ "?raw=true", "?raw=true&pending=true", } for _, queryParam := range queryParams { - res := httpGetAndCheckResponseStatus(t, ts.URL+"/transactions/"+nonExistingTxId+queryParam, 200) + res := httpGetAndCheckResponseStatus(t, ts.URL+"/transactions/"+nonExistingTxID+queryParam, 200) assert.Equal(t, "null\n", string(res)) } diff --git a/api/utils/http_test.go b/api/utils/http_test.go index e8ca39e43..237bb9b77 100644 --- a/api/utils/http_test.go +++ b/api/utils/http_test.go @@ -19,7 +19,7 @@ import ( ) func TestWrapHandlerFunc(t *testing.T) { - handlerFunc := func(w http.ResponseWriter, r *http.Request) error { + handlerFunc := func(_ http.ResponseWriter, r *http.Request) error { return nil } wrapped := utils.WrapHandlerFunc(handlerFunc) @@ -32,7 +32,7 @@ func TestWrapHandlerFunc(t *testing.T) { func TestWrapHandlerFuncWithGenericError(t *testing.T) { genericErrorMsg := "This is a generic error request" - handlerFunc := func(w http.ResponseWriter, r *http.Request) error { + handlerFunc := func(_ http.ResponseWriter, r *http.Request) error { return errors.New(genericErrorMsg) } wrapped := utils.WrapHandlerFunc(handlerFunc) @@ -45,7 +45,7 @@ func TestWrapHandlerFuncWithGenericError(t *testing.T) { func TestWrapHandlerFuncWithBadRequestError(t *testing.T) { badMsg := "This is a bad request" - handlerFunc := func(w http.ResponseWriter, r *http.Request) error { + handlerFunc := func(_ http.ResponseWriter, r *http.Request) error { return utils.BadRequest(errors.New(badMsg)) } wrapped := utils.WrapHandlerFunc(handlerFunc) @@ -92,13 +92,13 @@ func callWrappedFunc(wrapped *http.HandlerFunc) *httptest.ResponseRecorder { } type mockReader struct { - Id int + ID int Body string } func TestParseJSON(t *testing.T) { var parsedRes mockReader - body := mockReader{Id: 1, Body: "test"} + body := mockReader{ID: 1, Body: "test"} jsonBody, _ := json.Marshal(body) req := httptest.NewRequest("GET", "http://example.com", bytes.NewReader(jsonBody)) @@ -118,10 +118,10 @@ func TestWriteJSON(t *testing.T) { assert.Equal(t, http.StatusOK, rr.Code) assert.Equal(t, utils.JSONContentType, rr.Header().Get("Content-Type")) - respObj := mockReader{Id: 1, Body: "test"} + respObj := mockReader{ID: 1, Body: "test"} err = json.NewDecoder(rr.Body).Decode(&respObj) assert.NoError(t, err) - assert.Equal(t, body.Id, respObj.Id) + assert.Equal(t, body.ID, respObj.ID) assert.Equal(t, body.Body, respObj.Body) } diff --git a/bft/casts.go b/bft/casts.go index 30ab71727..9bb1e4ff8 100644 --- a/bft/casts.go +++ b/bft/casts.go @@ -15,7 +15,7 @@ import ( // casts stores the master's overall casts, maintaining the map of quality to checkpoint. type casts map[thor.Bytes32]uint32 -func (engine *BFTEngine) newCasts() error { +func (engine *Engine) newCasts() error { c := make(casts) finalized := engine.Finalized() diff --git a/bft/engine.go b/bft/engine.go index 925e469b2..d4e893702 100644 --- a/bft/engine.go +++ b/bft/engine.go @@ -35,9 +35,9 @@ type justified struct { value thor.Bytes32 } -// BFTEngine tracks all votes of blocks, computes the finalized checkpoint. +// Engine tracks all votes of blocks, computes the finalized checkpoint. // Not thread-safe! -type BFTEngine struct { +type Engine struct { repo *chain.Repository data kv.Store stater *state.Stater @@ -54,8 +54,8 @@ type BFTEngine struct { } // NewEngine creates a new bft engine. -func NewEngine(repo *chain.Repository, mainDB *muxdb.MuxDB, forkConfig thor.ForkConfig, master thor.Address) (*BFTEngine, error) { - engine := BFTEngine{ +func NewEngine(repo *chain.Repository, mainDB *muxdb.MuxDB, forkConfig thor.ForkConfig, master thor.Address) (*Engine, error) { + engine := Engine{ repo: repo, data: mainDB.NewStore(dataStoreName), stater: state.NewStater(mainDB), @@ -81,12 +81,12 @@ func NewEngine(repo *chain.Repository, mainDB *muxdb.MuxDB, forkConfig thor.Fork } // Finalized returns the finalized checkpoint. -func (engine *BFTEngine) Finalized() thor.Bytes32 { +func (engine *Engine) Finalized() thor.Bytes32 { return engine.finalized.Load().(thor.Bytes32) } // Justified returns the justified checkpoint. -func (engine *BFTEngine) Justified() (thor.Bytes32, error) { +func (engine *Engine) Justified() (thor.Bytes32, error) { head := engine.repo.BestBlockSummary().Header finalized := engine.Finalized() @@ -134,7 +134,7 @@ func (engine *BFTEngine) Justified() (thor.Bytes32, error) { } // Accepts checks if the given block is on the same branch of finalized checkpoint. -func (engine *BFTEngine) Accepts(parentID thor.Bytes32) (bool, error) { +func (engine *Engine) Accepts(parentID thor.Bytes32) (bool, error) { finalized := engine.Finalized() if block.Number(finalized) != 0 { @@ -145,7 +145,7 @@ func (engine *BFTEngine) Accepts(parentID thor.Bytes32) (bool, error) { } // Select selects between the new block and the current best, return true if new one is better. -func (engine *BFTEngine) Select(header *block.Header) (bool, error) { +func (engine *Engine) Select(header *block.Header) (bool, error) { newSt, err := engine.computeState(header) if err != nil { return false, err @@ -165,7 +165,7 @@ func (engine *BFTEngine) Select(header *block.Header) (bool, error) { } // CommitBlock commits bft state to storage. -func (engine *BFTEngine) CommitBlock(header *block.Header, isPacking bool) error { +func (engine *Engine) CommitBlock(header *block.Header, isPacking bool) error { // save quality and finalized at the end of each round if getStorePoint(header.Number()) == header.Number() { state, err := engine.computeState(header) @@ -211,7 +211,7 @@ func (engine *BFTEngine) CommitBlock(header *block.Header, isPacking bool) error // ShouldVote decides if vote COM for a given parent block ID. // Packer only. -func (engine *BFTEngine) ShouldVote(parentID thor.Bytes32) (bool, error) { +func (engine *Engine) ShouldVote(parentID thor.Bytes32) (bool, error) { // laze init casts if engine.casts == nil { if err := engine.newCasts(); err != nil { @@ -286,7 +286,7 @@ func (engine *BFTEngine) ShouldVote(parentID thor.Bytes32) (bool, error) { } // computeState computes the bft state regarding the given block header to the closest checkpoint. -func (engine *BFTEngine) computeState(header *block.Header) (*bftState, error) { +func (engine *Engine) computeState(header *block.Header) (*bftState, error) { if cached, ok := engine.caches.state.Get(header.ID()); ok { return cached.(*bftState), nil } @@ -320,7 +320,7 @@ func (engine *BFTEngine) computeState(header *block.Header) (*bftState, error) { } signer, _ := h.Signer() - js.AddBlock(h.ID(), signer, h.COM()) + js.AddBlock(signer, h.COM()) if h.Number() <= end { break @@ -341,7 +341,7 @@ func (engine *BFTEngine) computeState(header *block.Header) (*bftState, error) { // findCheckpointByQuality finds the first checkpoint reaches the given quality. // It is caller's responsibility to ensure the epoch that headID belongs to is concluded. -func (engine *BFTEngine) findCheckpointByQuality(target uint32, finalized, headID thor.Bytes32) (blockID thor.Bytes32, err error) { +func (engine *Engine) findCheckpointByQuality(target uint32, finalized, headID thor.Bytes32) (blockID thor.Bytes32, err error) { defer func() { if e := recover(); e != nil { err = e.(error) @@ -391,7 +391,7 @@ func (engine *BFTEngine) findCheckpointByQuality(target uint32, finalized, headI return c.GetBlockID(searchStart + uint32(num)*thor.CheckpointInterval) } -func (engine *BFTEngine) getMaxBlockProposers(sum *chain.BlockSummary) (uint64, error) { +func (engine *Engine) getMaxBlockProposers(sum *chain.BlockSummary) (uint64, error) { state := engine.stater.NewState(sum.Header.StateRoot(), sum.Header.Number(), sum.Conflicts, sum.SteadyNum) params, err := builtin.Params.Native(state).Get(thor.KeyMaxBlockProposers) if err != nil { @@ -405,7 +405,7 @@ func (engine *BFTEngine) getMaxBlockProposers(sum *chain.BlockSummary) (uint64, return mbp, nil } -func (engine *BFTEngine) getQuality(id thor.Bytes32) (quality uint32, err error) { +func (engine *Engine) getQuality(id thor.Bytes32) (quality uint32, err error) { if cached, ok := engine.caches.quality.Get(id); ok { return cached.(uint32), nil } diff --git a/bft/engine_test.go b/bft/engine_test.go index 2480bbf79..4c43aa87f 100644 --- a/bft/engine_test.go +++ b/bft/engine_test.go @@ -20,7 +20,7 @@ import ( ) type TestBFT struct { - engine *BFTEngine + engine *Engine db *muxdb.MuxDB repo *chain.Repository stater *state.Stater @@ -728,10 +728,8 @@ func TestJustifier(t *testing.T) { t.Fatal(err) } - var blkID thor.Bytes32 for i := 0; i <= MaxBlockProposers*2/3; i++ { - blkID = datagen.RandomHash() - vs.AddBlock(blkID, datagen.RandomAddress(), true) + vs.AddBlock(datagen.RandomAddress(), true) } st := vs.Summarize() @@ -740,7 +738,7 @@ func TestJustifier(t *testing.T) { assert.True(t, st.Committed) // add vote after commits,commit/justify stays the same - vs.AddBlock(datagen.RandomHash(), datagen.RandomAddress(), true) + vs.AddBlock(datagen.RandomAddress(), true) st = vs.Summarize() assert.Equal(t, uint32(3), st.Quality) assert.True(t, st.Justified) @@ -761,10 +759,8 @@ func TestJustifier(t *testing.T) { t.Fatal(err) } - var blkID thor.Bytes32 for i := 0; i <= MaxBlockProposers*2/3; i++ { - blkID = datagen.RandomHash() - vs.AddBlock(blkID, datagen.RandomAddress(), false) + vs.AddBlock(datagen.RandomAddress(), false) } st := vs.Summarize() @@ -787,34 +783,29 @@ func TestJustifier(t *testing.T) { t.Fatal(err) } - var blkID thor.Bytes32 // vote times COM for i := 0; i < MaxBlockProposers*2/3; i++ { - blkID = datagen.RandomHash() - vs.AddBlock(blkID, datagen.RandomAddress(), true) + vs.AddBlock(datagen.RandomAddress(), true) } master := datagen.RandomAddress() // master votes WIT - blkID = datagen.RandomHash() - vs.AddBlock(blkID, master, false) + vs.AddBlock(master, false) // justifies but not committed st := vs.Summarize() assert.True(t, st.Justified) assert.False(t, st.Committed) - blkID = datagen.RandomHash() // master votes COM - vs.AddBlock(blkID, master, true) + vs.AddBlock(master, true) // should not be committed st = vs.Summarize() assert.False(t, st.Committed) // another master votes WIT - blkID = datagen.RandomHash() - vs.AddBlock(blkID, datagen.RandomAddress(), true) + vs.AddBlock(datagen.RandomAddress(), true) st = vs.Summarize() assert.True(t, st.Committed) }, @@ -831,19 +822,19 @@ func TestJustifier(t *testing.T) { } master := datagen.RandomAddress() - vs.AddBlock(datagen.RandomHash(), master, true) + vs.AddBlock(master, true) assert.Equal(t, true, vs.votes[master]) assert.Equal(t, uint64(1), vs.comVotes) - vs.AddBlock(datagen.RandomHash(), master, false) + vs.AddBlock(master, false) assert.Equal(t, false, vs.votes[master]) assert.Equal(t, uint64(0), vs.comVotes) - vs.AddBlock(datagen.RandomHash(), master, true) + vs.AddBlock(master, true) assert.Equal(t, false, vs.votes[master]) assert.Equal(t, uint64(0), vs.comVotes) - vs.AddBlock(datagen.RandomHash(), master, false) + vs.AddBlock(master, false) assert.Equal(t, false, vs.votes[master]) assert.Equal(t, uint64(0), vs.comVotes) @@ -851,19 +842,19 @@ func TestJustifier(t *testing.T) { if err != nil { t.Fatal(err) } - vs.AddBlock(datagen.RandomHash(), master, false) + vs.AddBlock(master, false) assert.Equal(t, false, vs.votes[master]) assert.Equal(t, uint64(0), vs.comVotes) - vs.AddBlock(datagen.RandomHash(), master, true) + vs.AddBlock(master, true) assert.Equal(t, false, vs.votes[master]) assert.Equal(t, uint64(0), vs.comVotes) - vs.AddBlock(datagen.RandomHash(), master, true) + vs.AddBlock(master, true) assert.Equal(t, false, vs.votes[master]) assert.Equal(t, uint64(0), vs.comVotes) - vs.AddBlock(datagen.RandomHash(), master, false) + vs.AddBlock(master, false) assert.Equal(t, false, vs.votes[master]) assert.Equal(t, uint64(0), vs.comVotes) }, diff --git a/bft/justifier.go b/bft/justifier.go index eb85ab4e9..8906e7f27 100644 --- a/bft/justifier.go +++ b/bft/justifier.go @@ -26,7 +26,7 @@ type justifier struct { comVotes uint64 } -func (engine *BFTEngine) newJustifier(parentID thor.Bytes32) (*justifier, error) { +func (engine *Engine) newJustifier(parentID thor.Bytes32) (*justifier, error) { blockNum := block.Number(parentID) + 1 var lastOfParentRound uint32 @@ -67,7 +67,7 @@ func (engine *BFTEngine) newJustifier(parentID thor.Bytes32) (*justifier, error) } // AddBlock adds a new block to the set. -func (js *justifier) AddBlock(blockID thor.Bytes32, signer thor.Address, isCOM bool) { +func (js *justifier) AddBlock(signer thor.Address, isCOM bool) { if prev, ok := js.votes[signer]; !ok { js.votes[signer] = isCOM if isCOM { diff --git a/block/block_test.go b/block/block_test.go index 5a7912c55..547aede6e 100644 --- a/block/block_test.go +++ b/block/block_test.go @@ -12,7 +12,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/rlp" "github.com/stretchr/testify/assert" - . "github.com/vechain/thor/v2/block" + "github.com/vechain/thor/v2/block" "github.com/vechain/thor/v2/thor" "github.com/vechain/thor/v2/tx" ) @@ -33,7 +33,7 @@ func TestBlock(t *testing.T) { beneficiary thor.Address = thor.BytesToAddress([]byte("abc")) ) - block := new(Builder). + blk := new(block.Builder). GasUsed(gasUsed). Transaction(tx1). Transaction(tx2). @@ -46,12 +46,12 @@ func TestBlock(t *testing.T) { Beneficiary(beneficiary). Build() - h := block.Header() + h := blk.Header() - txs := block.Transactions() + txs := blk.Transactions() txsRootHash := txs.RootHash() - assert.Equal(t, Compose(h, txs), block) + assert.Equal(t, block.Compose(h, txs), blk) assert.Equal(t, gasLimit, h.GasLimit()) assert.Equal(t, gasUsed, h.GasUsed()) assert.Equal(t, totalScore, h.TotalScore()) @@ -63,16 +63,16 @@ func TestBlock(t *testing.T) { assert.Equal(t, txsRootHash, h.TxsRoot()) key, _ := crypto.HexToECDSA(privKey) - sig, _ := crypto.Sign(block.Header().SigningHash().Bytes(), key) + sig, _ := crypto.Sign(blk.Header().SigningHash().Bytes(), key) - block = block.WithSignature(sig) + blk = blk.WithSignature(sig) - data, _ := rlp.EncodeToBytes(block) + data, _ := rlp.EncodeToBytes(blk) - b := Block{} + b := block.Block{} rlp.DecodeBytes(data, &b) - block = new(Builder). + blk = new(block.Builder). GasUsed(gasUsed). GasLimit(gasLimit). TotalScore(totalScore). @@ -84,13 +84,13 @@ func TestBlock(t *testing.T) { TransactionFeatures(1). Build() - sig, _ = crypto.Sign(block.Header().SigningHash().Bytes(), key) - block = block.WithSignature(sig) + sig, _ = crypto.Sign(blk.Header().SigningHash().Bytes(), key) + blk = blk.WithSignature(sig) - assert.Equal(t, tx.Features(1), block.Header().TxsFeatures()) - data, _ = rlp.EncodeToBytes(block) - var bx Block + assert.Equal(t, tx.Features(1), blk.Header().TxsFeatures()) + data, _ = rlp.EncodeToBytes(blk) + var bx block.Block assert.Nil(t, rlp.DecodeBytes(data, &bx)) - assert.Equal(t, block.Header().ID(), bx.Header().ID()) - assert.Equal(t, block.Header().TxsFeatures(), bx.Header().TxsFeatures()) + assert.Equal(t, blk.Header().ID(), bx.Header().ID()) + assert.Equal(t, blk.Header().TxsFeatures(), bx.Header().TxsFeatures()) } diff --git a/block/header_test.go b/block/header_test.go index 2da70bb4c..141dfe804 100644 --- a/block/header_test.go +++ b/block/header_test.go @@ -89,12 +89,12 @@ func TestHeaderEncoding(t *testing.T) { rand.Read(proof[:]) // nolint rand.Read(alpha[:]) // nolint - complex, err := NewComplexSignature(sig[:], proof[:]) + cplx, err := NewComplexSignature(sig[:], proof[:]) if err != nil { t.Fatal(err) } - b1 := new(Builder).Alpha(alpha[:]).Build().WithSignature(complex[:]) + b1 := new(Builder).Alpha(alpha[:]).Build().WithSignature(cplx[:]) bs1, err := rlp.EncodeToBytes(b1.Header()) if err != nil { t.Fatal(err) diff --git a/chain/repository.go b/chain/repository.go index a1ed0c7e2..2460d6a3c 100644 --- a/chain/repository.go +++ b/chain/repository.go @@ -102,11 +102,11 @@ func NewRepository(db *muxdb.MuxDB, genesis *block.Block) (*Repository, error) { return nil, errors.New("genesis mismatch") } - if summary, err := repo.GetBlockSummary(bestID); err != nil { + summary, err := repo.GetBlockSummary(bestID) + if err != nil { return nil, errors.Wrap(err, "get best block") - } else { - repo.bestSummary.Store(summary) } + repo.bestSummary.Store(summary) } if val, err := repo.props.Get(steadyBlockIDKey); err != nil { diff --git a/chain/repository_test.go b/chain/repository_test.go index 08a23c037..1391acb8d 100644 --- a/chain/repository_test.go +++ b/chain/repository_test.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/assert" "github.com/vechain/thor/v2/block" - . "github.com/vechain/thor/v2/chain" + "github.com/vechain/thor/v2/chain" "github.com/vechain/thor/v2/genesis" "github.com/vechain/thor/v2/muxdb" "github.com/vechain/thor/v2/state" @@ -23,20 +23,20 @@ func M(args ...interface{}) []interface{} { return args } -func newTestRepo() (*muxdb.MuxDB, *Repository) { +func newTestRepo() (*muxdb.MuxDB, *chain.Repository) { db := muxdb.NewMem() g := genesis.NewDevnet() b0, _, _, _ := g.Build(state.NewStater(db)) - repo, err := NewRepository(db, b0) + repo, err := chain.NewRepository(db, b0) if err != nil { panic(err) } return db, repo } -func reopenRepo(db *muxdb.MuxDB, b0 *block.Block) *Repository { - repo, err := NewRepository(db, b0) +func reopenRepo(db *muxdb.MuxDB, b0 *block.Block) *chain.Repository { + repo, err := chain.NewRepository(db, b0) if err != nil { panic(err) } @@ -63,7 +63,7 @@ func TestRepository(t *testing.T) { g := genesis.NewDevnet() b0, _, _, _ := g.Build(state.NewStater(db)) - repo1, err := NewRepository(db, b0) + repo1, err := chain.NewRepository(db, b0) if err != nil { panic(err) } @@ -81,8 +81,8 @@ func TestRepository(t *testing.T) { assert.Equal(t, uint32(0), repo1.BestBlockSummary().Header.Number()) repo1.SetBestBlockID(b1.Header().ID()) - repo2, _ := NewRepository(db, b0) - for _, repo := range []*Repository{repo1, repo2} { + repo2, _ := chain.NewRepository(db, b0) + for _, repo := range []*chain.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/main.go b/cmd/thor/main.go index a165b9d06..e1ead8caf 100644 --- a/cmd/thor/main.go +++ b/cmd/thor/main.go @@ -171,22 +171,22 @@ func defaultAction(ctx *cli.Context) error { metricsURL := "" if ctx.Bool(enableMetricsFlag.Name) { metrics.InitializePrometheusMetrics() - url, close, err := api.StartMetricsServer(ctx.String(metricsAddrFlag.Name)) + url, closeFunc, err := api.StartMetricsServer(ctx.String(metricsAddrFlag.Name)) if err != nil { return fmt.Errorf("unable to start metrics server - %w", err) } metricsURL = url - defer func() { log.Info("stopping metrics server..."); close() }() + defer func() { log.Info("stopping metrics server..."); closeFunc() }() } adminURL := "" if ctx.Bool(enableAdminFlag.Name) { - url, close, err := api.StartAdminServer(ctx.String(adminAddrFlag.Name), logLevel) + url, closeFunc, err := api.StartAdminServer(ctx.String(adminAddrFlag.Name), logLevel) if err != nil { return fmt.Errorf("unable to start admin server - %w", err) } adminURL = url - defer func() { log.Info("stopping admin server..."); close() }() + defer func() { log.Info("stopping admin server..."); closeFunc() }() } gene, forkConfig, err := selectGenesis(ctx) @@ -315,22 +315,22 @@ func soloAction(ctx *cli.Context) error { metricsURL := "" if ctx.Bool(enableMetricsFlag.Name) { metrics.InitializePrometheusMetrics() - url, close, err := api.StartMetricsServer(ctx.String(metricsAddrFlag.Name)) + url, closeFunc, err := api.StartMetricsServer(ctx.String(metricsAddrFlag.Name)) if err != nil { return fmt.Errorf("unable to start metrics server - %w", err) } metricsURL = url - defer func() { log.Info("stopping metrics server..."); close() }() + defer func() { log.Info("stopping metrics server..."); closeFunc() }() } adminURL := "" if ctx.Bool(enableAdminFlag.Name) { - url, close, err := api.StartAdminServer(ctx.String(adminAddrFlag.Name), logLevel) + url, closeFunc, err := api.StartAdminServer(ctx.String(adminAddrFlag.Name), logLevel) if err != nil { return fmt.Errorf("unable to start admin server - %w", err) } adminURL = url - defer func() { log.Info("stopping admin server..."); close() }() + defer func() { log.Info("stopping admin server..."); closeFunc() }() } var ( diff --git a/cmd/thor/node/node.go b/cmd/thor/node/node.go index 663ff185f..e4b53a3c0 100644 --- a/cmd/thor/node/node.go +++ b/cmd/thor/node/node.go @@ -50,7 +50,7 @@ type Node struct { cons *consensus.Consensus master *Master repo *chain.Repository - bft *bft.BFTEngine + bft *bft.Engine logDB *logdb.LogDB txPool *txpool.TxPool txStashPath string @@ -69,7 +69,7 @@ type Node struct { func New( master *Master, repo *chain.Repository, - bft *bft.BFTEngine, + bft *bft.Engine, stater *state.Stater, logDB *logdb.LogDB, txPool *txpool.TxPool, @@ -484,28 +484,28 @@ func (n *Node) processFork(newBlock *block.Block, oldBestBlockID thor.Bytes32) { oldTrunk := n.repo.NewChain(oldBestBlockID) newTrunk := n.repo.NewChain(newBlock.Header().ParentID()) - sideIds, err := oldTrunk.Exclude(newTrunk) + sideIDs, err := oldTrunk.Exclude(newTrunk) if err != nil { logger.Warn("failed to process fork", "err", err) return } // Set the gauge metric to the size of the fork (0 if there are no forks) - metricChainForkSize().Set(int64(len(sideIds))) + metricChainForkSize().Set(int64(len(sideIDs))) - if len(sideIds) == 0 { + if len(sideIDs) == 0 { return } - if n := len(sideIds); n >= 2 { + if n := len(sideIDs); n >= 2 { metricChainForkCount().Add(1) logger.Warn(fmt.Sprintf( `⑂⑂⑂⑂⑂⑂⑂⑂ FORK HAPPENED ⑂⑂⑂⑂⑂⑂⑂⑂ side-chain: %v %v`, - n, sideIds[n-1])) + n, sideIDs[n-1])) } - for _, id := range sideIds { + for _, id := range sideIDs { b, err := n.repo.GetBlock(id) if err != nil { logger.Warn("failed to process fork", "err", err) diff --git a/cmd/thor/node/stats_test.go b/cmd/thor/node/stats_test.go index c72cbeb6b..13ec5b4e3 100644 --- a/cmd/thor/node/stats_test.go +++ b/cmd/thor/node/stats_test.go @@ -20,10 +20,10 @@ func TestUpdateProcessed(t *testing.T) { txs := 5 exec := mclock.AbsTime(100) commit := mclock.AbsTime(200) - real := mclock.AbsTime(300) + realTime := mclock.AbsTime(300) usedGas := uint64(5000) - s.UpdateProcessed(n, txs, exec, commit, real, usedGas) + s.UpdateProcessed(n, txs, exec, commit, realTime, usedGas) assert.Equal(t, 10, s.processed, "processed count mismatch") assert.Equal(t, 5, s.txs, "txs count mismatch") diff --git a/cmd/thor/optimizer/optimizer_test.go b/cmd/thor/optimizer/optimizer_test.go index 407c07f53..af3f729c7 100644 --- a/cmd/thor/optimizer/optimizer_test.go +++ b/cmd/thor/optimizer/optimizer_test.go @@ -134,7 +134,7 @@ func newTempFileDB() (*muxdb.MuxDB, func() error, error) { return nil, nil, err } - close := func() error { + closeFunc := func() error { err = db.Close() if err != nil { return err @@ -146,7 +146,7 @@ func newTempFileDB() (*muxdb.MuxDB, func() error, error) { return nil } - return db, close, nil + return db, closeFunc, nil } func TestProcessDump(t *testing.T) { @@ -224,7 +224,7 @@ func TestWaitUntil(t *testing.T) { } parentID := b0.Header().ID() - var parentScore uint64 = 0 + var parentScore uint64 for i := 0; i < 6; i++ { blk := newBlock(parentID, parentScore+2, b0.Header().StateRoot(), devAccounts[0].PrivateKey) err := repo.AddBlock(blk, tx.Receipts{}, 0) diff --git a/genesis/customnet_test.go b/genesis/customnet_test.go index 2ea41fca2..27d8d0461 100644 --- a/genesis/customnet_test.go +++ b/genesis/customnet_test.go @@ -157,9 +157,9 @@ func TestHexOrDecimal256MarshalUnmarshal(t *testing.T) { // Marshal the value back to JSON // using direct function - directMarshallJson, err := unmarshaledValue.MarshalJSON() + directMarshallJSON, err := unmarshaledValue.MarshalJSON() assert.NoError(t, err, "Marshaling should not produce an error") - assert.Equal(t, originalHex, string(directMarshallJson)) + assert.Equal(t, originalHex, string(directMarshallJSON)) // using json overloading ( satisfies the json.Unmarshal interface ) // using value diff --git a/kv/bucket_test.go b/kv/bucket_test.go index a18b0050d..3d396a821 100644 --- a/kv/bucket_test.go +++ b/kv/bucket_test.go @@ -37,7 +37,7 @@ func (m mem) Delete(k []byte) error { delete(m, string(k)) return nil } -func (m mem) IsNotFound(err error) bool { +func (m mem) IsNotFound(error) bool { return true } @@ -156,7 +156,7 @@ func (s *DummyStore) Delete(key []byte) error { return nil } -func (s *DummyStore) DeleteRange(ctx context.Context, r Range) error { +func (s *DummyStore) DeleteRange(_ context.Context, r Range) error { for k := range s.data { if k >= string(r.Start) && k < string(r.Limit) { delete(s.data, k) @@ -165,7 +165,7 @@ func (s *DummyStore) DeleteRange(ctx context.Context, r Range) error { return nil } -func (s *DummyStore) Iterate(r Range) Iterator { +func (s *DummyStore) Iterate(_ Range) Iterator { return &DummyIterator{} } @@ -180,11 +180,11 @@ func (s *DummyStore) Snapshot() Snapshot { // Dummy Bulk Implementation type DummyBulk struct{} -func (db *DummyBulk) Put(key, val []byte) error { +func (db *DummyBulk) Put(_, _ []byte) error { return nil } -func (db *DummyBulk) Delete(key []byte) error { +func (db *DummyBulk) Delete(_ []byte) error { return nil } @@ -232,7 +232,7 @@ func (di *DummyIterator) Error() error { // Dummy Snapshot implementation type DummySnapshot struct{} -func (ds *DummySnapshot) Get(key []byte) ([]byte, error) { +func (ds *DummySnapshot) Get(_ []byte) ([]byte, error) { return nil, errors.New("key not found") } diff --git a/log/handler.go b/log/handler.go index 2cc150fa4..df08c8632 100644 --- a/log/handler.go +++ b/log/handler.go @@ -36,19 +36,19 @@ func DiscardHandler() slog.Handler { return &discardHandler{} } -func (h *discardHandler) Handle(_ context.Context, r slog.Record) error { +func (h *discardHandler) Handle(_ context.Context, _ slog.Record) error { return nil } -func (h *discardHandler) Enabled(_ context.Context, level slog.Level) bool { +func (h *discardHandler) Enabled(_ context.Context, _ slog.Level) bool { return false } -func (h *discardHandler) WithGroup(name string) slog.Handler { +func (h *discardHandler) WithGroup(_ string) slog.Handler { panic("not implemented") } -func (h *discardHandler) WithAttrs(attrs []slog.Attr) slog.Handler { +func (h *discardHandler) WithAttrs(_ []slog.Attr) slog.Handler { return &discardHandler{} } @@ -104,7 +104,7 @@ func (h *TerminalHandler) Enabled(_ context.Context, level slog.Level) bool { return level.Level() >= h.lvl.Level() } -func (h *TerminalHandler) WithGroup(name string) slog.Handler { +func (h *TerminalHandler) WithGroup(_ string) slog.Handler { panic("not implemented") } @@ -119,10 +119,10 @@ func (h *TerminalHandler) WithAttrs(attrs []slog.Attr) slog.Handler { } // ResetFieldPadding zeroes the field-padding for all attribute pairs. -func (t *TerminalHandler) ResetFieldPadding() { - t.mu.Lock() - t.fieldPadding = make(map[string]int) - t.mu.Unlock() +func (h *TerminalHandler) ResetFieldPadding() { + h.mu.Lock() + h.fieldPadding = make(map[string]int) + h.mu.Unlock() } type leveler struct{ minLevel *slog.LevelVar } diff --git a/logdb/logdb_bench_test.go b/logdb/logdb_bench_test.go index c1dd2c6e7..e421ffce3 100644 --- a/logdb/logdb_bench_test.go +++ b/logdb/logdb_bench_test.go @@ -109,7 +109,7 @@ func BenchmarkFakeDB_WriteBlocks(t *testing.B) { }{ { "repeated writes", - func(b *testing.B) { + func(_ *testing.B) { for i := 0; i < writeCount; i++ { blk = new(block.Builder). ParentID(blk.Header().ID()). @@ -123,7 +123,7 @@ func BenchmarkFakeDB_WriteBlocks(t *testing.B) { }, { "batched writes", - func(b *testing.B) { + func(_ *testing.B) { for i := 0; i < writeCount; i++ { blk = new(block.Builder). ParentID(blk.Header().ID()). diff --git a/metrics/noop.go b/metrics/noop.go index 6f782dc31..6eb909ff9 100644 --- a/metrics/noop.go +++ b/metrics/noop.go @@ -35,7 +35,7 @@ var noopMetric = noopMeters{} type noopMeters struct{} -func (n noopMeters) ObserveWithLabels(i int64, m map[string]string) {} +func (n noopMeters) ObserveWithLabels(_ int64, _ map[string]string) {} func (n noopMeters) AddWithLabel(int64, map[string]string) {} diff --git a/muxdb/internal/trie/trie.go b/muxdb/internal/trie/trie.go index 1cf5c74e7..af58fc78f 100644 --- a/muxdb/internal/trie/trie.go +++ b/muxdb/internal/trie/trie.go @@ -168,9 +168,8 @@ func (t *Trie) newDatabase() trie.Database { keyBuf = t.makeDedupedNodeKey(keyBuf[:0], thisSeq, thisPath) if val, err := snapshot.Get(keyBuf); err == nil { return append(dst, val...), nil - } else { - return nil, err } + return nil, err }), databaseKeyEncodeFunc(func(hash []byte, seq uint64, path []byte) []byte { thisHash = hash @@ -295,7 +294,7 @@ func (t *Trie) Stage(newCommitNum, newDistinctNum uint32) (root thor.Bytes32, co } return nil }), - databaseKeyEncodeFunc(func(hash []byte, seq uint64, path []byte) []byte { + databaseKeyEncodeFunc(func(_ []byte, _ uint64, path []byte) []byte { thisPath = path return nil }), diff --git a/p2psrv/rpc/rpc.go b/p2psrv/rpc/rpc.go index 1bbab7bb5..911ded75b 100644 --- a/p2psrv/rpc/rpc.go +++ b/p2psrv/rpc/rpc.go @@ -179,7 +179,7 @@ func (r *RPC) finalizeCall(id uint32) { } // Notify notifies a message to the peer. -func (r *RPC) Notify(ctx context.Context, msgCode uint64, arg interface{}) error { +func (r *RPC) Notify(_ context.Context, msgCode uint64, arg interface{}) error { return p2p.Send(r.rw, msgCode, &msgData{0, false, arg}) } diff --git a/p2psrv/server.go b/p2psrv/server.go index cb3422cb4..c17240bb1 100644 --- a/p2psrv/server.go +++ b/p2psrv/server.go @@ -356,11 +356,11 @@ func (s *Server) fetchBootstrap() { } for { - if err := f(); err == nil || errors.Is(err, context.Canceled) { + err := f() + if err == nil || errors.Is(err, context.Canceled) { return - } else { - logger.Warn("update bootstrap nodes from remote failed", "err", err) } + logger.Warn("update bootstrap nodes from remote failed", "err", err) select { case <-ctx.Done(): diff --git a/packer/packer_test.go b/packer/packer_test.go index a099a3d01..4898804e4 100644 --- a/packer/packer_test.go +++ b/packer/packer_test.go @@ -34,7 +34,7 @@ type txIterator struct { i int } -var nonce uint64 = uint64(time.Now().UnixNano()) +var nonce = uint64(time.Now().UnixNano()) func (ti *txIterator) HasNext() bool { return ti.i < 100 @@ -61,7 +61,7 @@ func (ti *txIterator) Next() *tx.Transaction { return tx } -func (ti *txIterator) OnProcessed(txID thor.Bytes32, err error) { +func (ti *txIterator) OnProcessed(_ thor.Bytes32, _ error) { } func TestP(t *testing.T) { diff --git a/poa/candidates.go b/poa/candidates.go index f384e1fe4..ceaedab82 100644 --- a/poa/candidates.go +++ b/poa/candidates.go @@ -44,8 +44,8 @@ func NewCandidates(list []*authority.Candidate) *Candidates { // Copy make a copy. func (c *Candidates) Copy() *Candidates { c.referenced = true - copy := *c - return © + cpy := *c + return &cpy } // Pick picks a list of proposers, which satisfy preset conditions. @@ -100,9 +100,9 @@ func (c *Candidates) Update(addr thor.Address, active bool) bool { c.list = append([]*authority.Candidate(nil), c.list...) c.referenced = false } - copy := *c.list[i] - copy.Active = active - c.list[i] = © + cpy := *c.list[i] + cpy.Active = active + c.list[i] = &cpy return true } return false diff --git a/runtime/statedb/statedb.go b/runtime/statedb/statedb.go index c0f496d10..37f813148 100644 --- a/runtime/statedb/statedb.go +++ b/runtime/statedb/statedb.go @@ -87,7 +87,7 @@ func (s *StateDB) GetLogs() (tx.Events, tx.Transfers) { // } // CreateAccount stub. -func (s *StateDB) CreateAccount(addr common.Address) {} +func (s *StateDB) CreateAccount(_ common.Address) {} // GetBalance stub. func (s *StateDB) GetBalance(addr common.Address) *big.Int { @@ -127,10 +127,10 @@ func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) { } // GetNonce stub. -func (s *StateDB) GetNonce(addr common.Address) uint64 { return 0 } +func (s *StateDB) GetNonce(_ common.Address) uint64 { return 0 } // SetNonce stub. -func (s *StateDB) SetNonce(addr common.Address, nonce uint64) {} +func (s *StateDB) SetNonce(_ common.Address, _ uint64) {} // GetCodeHash stub. func (s *StateDB) GetCodeHash(addr common.Address) common.Hash { diff --git a/runtime/statedb/statedb_test.go b/runtime/statedb/statedb_test.go index 578850c4d..422c9e1ce 100644 --- a/runtime/statedb/statedb_test.go +++ b/runtime/statedb/statedb_test.go @@ -100,13 +100,13 @@ func newTestAction(addr common.Address, r *rand.Rand) testAction { }, { name: "CreateAccount", - fn: func(a testAction, s *statedb.StateDB) { + fn: func(_ testAction, s *statedb.StateDB) { s.CreateAccount(addr) }, }, { name: "Suicide", - fn: func(a testAction, s *statedb.StateDB) { + fn: func(_ testAction, s *statedb.StateDB) { s.Suicide(addr) }, }, diff --git a/stackedmap/stackedmap_test.go b/stackedmap/stackedmap_test.go index d9dbedec8..caeb950a4 100644 --- a/stackedmap/stackedmap_test.go +++ b/stackedmap/stackedmap_test.go @@ -58,7 +58,7 @@ func TestStackedMap(t *testing.T) { func TestStackedMapPuts(t *testing.T) { assert := assert.New(t) - sm := stackedmap.New(func(key interface{}) (interface{}, bool, error) { + sm := stackedmap.New(func(_ interface{}) (interface{}, bool, error) { return nil, false, nil }) @@ -87,7 +87,7 @@ func TestStackedMapPuts(t *testing.T) { assert.Equal(len(kvs), i, "Journal traverse should abort") i = 0 - sm.Journal(func(k, v interface{}) bool { + sm.Journal(func(_, _ interface{}) bool { i++ return false }) diff --git a/thor/bytes32_test.go b/thor/bytes32_test.go index 24ec105fc..6da73f4f4 100644 --- a/thor/bytes32_test.go +++ b/thor/bytes32_test.go @@ -28,9 +28,9 @@ func TestMarshalUnmarshal(t *testing.T) { // Marshal the value back to JSON // using direct function - directMarshallJson, err := unmarshaledValue.MarshalJSON() + directMarshallJSON, err := unmarshaledValue.MarshalJSON() assert.NoError(t, err, "Marshaling should not produce an error") - assert.Equal(t, originalHex, string(directMarshallJson)) + assert.Equal(t, originalHex, string(directMarshallJSON)) // using json overloading ( satisfies the json.Unmarshal interface ) // using value diff --git a/thor/fork_config.go b/thor/fork_config.go index 185d24366..19e0b48b4 100644 --- a/thor/fork_config.go +++ b/thor/fork_config.go @@ -11,6 +11,7 @@ import ( "strings" ) +// nolint: revive // ForkConfig config for a fork. type ForkConfig struct { VIP191 uint32 diff --git a/tracers/js/goja.go b/tracers/js/goja.go index 86514213d..e6440980a 100644 --- a/tracers/js/goja.go +++ b/tracers/js/goja.go @@ -214,7 +214,7 @@ func (t *jsTracer) CaptureClauseEnd(restGas uint64) { } // CaptureStart implements the Tracer interface to initialize the tracing operation. -func (t *jsTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { +func (t *jsTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, _ uint64, value *big.Int) { t.env = env db := &dbObj{db: env.StateDB, vm: t.vm, toBig: t.toBig, toBuf: t.toBuf, fromBuf: t.fromBuf} t.dbValue = db.setupObject() @@ -241,7 +241,7 @@ func (t *jsTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Addr } // CaptureState implements the Tracer interface to trace a single step of VM execution. -func (t *jsTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, rData []byte, depth int, err error) { +func (t *jsTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, _ []byte, depth int, err error) { if !t.traceStep { return } @@ -278,7 +278,7 @@ func (t *jsTracer) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, memor } // CaptureEnd is called after the call finishes to finalize the tracing. -func (t *jsTracer) CaptureEnd(output []byte, gasUsed uint64, err error) { +func (t *jsTracer) CaptureEnd(output []byte, _ uint64, err error) { t.ctx["output"] = t.vm.ToValue(output) if err != nil { t.ctx["error"] = t.vm.ToValue(err.Error()) @@ -592,11 +592,11 @@ func (mo *memoryObj) Length() int { return mo.memory.Len() } -func (m *memoryObj) setupObject() *goja.Object { - o := m.vm.NewObject() - o.Set("slice", m.vm.ToValue(m.Slice)) - o.Set("getUint", m.vm.ToValue(m.GetUint)) - o.Set("length", m.vm.ToValue(m.Length)) +func (mo *memoryObj) setupObject() *goja.Object { + o := mo.vm.NewObject() + o.Set("slice", mo.vm.ToValue(mo.Slice)) + o.Set("getUint", mo.vm.ToValue(mo.GetUint)) + o.Set("length", mo.vm.ToValue(mo.Length)) return o } @@ -778,12 +778,12 @@ func (co *contractObj) GetInput() goja.Value { return res } -func (c *contractObj) setupObject() *goja.Object { - o := c.vm.NewObject() - o.Set("getCaller", c.vm.ToValue(c.GetCaller)) - o.Set("getAddress", c.vm.ToValue(c.GetAddress)) - o.Set("getValue", c.vm.ToValue(c.GetValue)) - o.Set("getInput", c.vm.ToValue(c.GetInput)) +func (co *contractObj) setupObject() *goja.Object { + o := co.vm.NewObject() + o.Set("getCaller", co.vm.ToValue(co.GetCaller)) + o.Set("getAddress", co.vm.ToValue(co.GetAddress)) + o.Set("getValue", co.vm.ToValue(co.GetValue)) + o.Set("getInput", co.vm.ToValue(co.GetInput)) return o } diff --git a/tracers/js/tracer_test.go b/tracers/js/tracer_test.go index 4954a7fb1..dca1d7e05 100644 --- a/tracers/js/tracer_test.go +++ b/tracers/js/tracer_test.go @@ -33,23 +33,23 @@ import ( type account struct{} -func (account) SubBalance(amount *big.Int) {} -func (account) AddBalance(amount *big.Int) {} -func (account) SetAddress(common.Address) {} -func (account) Value() *big.Int { return nil } -func (account) SetBalance(*big.Int) {} -func (account) SetNonce(uint64) {} -func (account) Balance() *big.Int { return nil } -func (account) Address() common.Address { return common.Address{} } -func (account) SetCode(common.Hash, []byte) {} -func (account) ForEachStorage(cb func(key, value common.Hash) bool) {} +func (account) SubBalance(_ *big.Int) {} +func (account) AddBalance(_ *big.Int) {} +func (account) SetAddress(_ common.Address) {} +func (account) Value() *big.Int { return nil } +func (account) SetBalance(_ *big.Int) {} +func (account) SetNonce(_ uint64) {} +func (account) Balance() *big.Int { return nil } +func (account) Address() common.Address { return common.Address{} } +func (account) SetCode(_ common.Hash, _ []byte) {} +func (account) ForEachStorage(_ func(key, value common.Hash) bool) {} type dummyStatedb struct { state.StateDB } -func (*dummyStatedb) GetRefund() uint64 { return 1337 } -func (*dummyStatedb) GetBalance(addr common.Address) *big.Int { return new(big.Int) } +func (*dummyStatedb) GetRefund() uint64 { return 1337 } +func (*dummyStatedb) GetBalance(_ common.Address) *big.Int { return new(big.Int) } func testCtx() vm.Context { return vm.Context{ diff --git a/tracers/logger/logger.go b/tracers/logger/logger.go index 654602bcd..68065a3bd 100644 --- a/tracers/logger/logger.go +++ b/tracers/logger/logger.go @@ -233,13 +233,13 @@ func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, err error) { } } -func (l *StructLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { +func (l *StructLogger) CaptureEnter(_ vm.OpCode, _ common.Address, _ common.Address, _ []byte, _ uint64, _ *big.Int) { } -func (l *StructLogger) CaptureExit(output []byte, gasUsed uint64, err error) { +func (l *StructLogger) CaptureExit(_ []byte, _ uint64, _ error) { } -func (l *StructLogger) SetContext(ctx *tracers.Context) { +func (l *StructLogger) SetContext(_ *tracers.Context) { } func (l *StructLogger) GetResult() (json.RawMessage, error) { @@ -332,7 +332,7 @@ func WriteLogs(writer io.Writer, logs []*types.Log) { } } -type mdLogger struct { +type MDLogger struct { out io.Writer cfg *Config env *vm.EVM @@ -340,15 +340,15 @@ type mdLogger struct { // NewMarkdownLogger creates a logger which outputs information in a format adapted // for human readability, and is also a valid markdown table -func NewMarkdownLogger(cfg *Config, writer io.Writer) *mdLogger { - l := &mdLogger{out: writer, cfg: cfg} +func NewMarkdownLogger(cfg *Config, writer io.Writer) *MDLogger { + l := &MDLogger{out: writer, cfg: cfg} if l.cfg == nil { l.cfg = &Config{} } return l } -func (t *mdLogger) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { +func (t *MDLogger) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { t.env = env if !create { fmt.Fprintf(t.out, "From: `%v`\nTo: `%v`\nData: `%#x`\nGas: `%d`\nValue `%v` wei\n", @@ -367,7 +367,7 @@ func (t *mdLogger) CaptureStart(env *vm.EVM, from common.Address, to common.Addr } // CaptureState also tracks SLOAD/SSTORE ops to track storage change. -func (t *mdLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, rData []byte, depth int, err error) { +func (t *MDLogger) CaptureState(pc uint64, op vm.OpCode, _, cost uint64, _ *vm.Memory, stack *vm.Stack, _ *vm.Contract, _ []byte, _ int, err error) { fmt.Fprintf(t.out, "| %4d | %10v | %3d |", pc, op, cost) if !t.cfg.DisableStack { @@ -386,23 +386,23 @@ func (t *mdLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, memor } } -func (t *mdLogger) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, depth int, err error) { +func (t *MDLogger) CaptureFault(pc uint64, op vm.OpCode, _, _ uint64, _ *vm.Memory, _ *vm.Stack, _ *vm.Contract, _ int, err error) { fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err) } -func (t *mdLogger) CaptureEnd(output []byte, gasUsed uint64, err error) { +func (t *MDLogger) CaptureEnd(output []byte, gasUsed uint64, err error) { fmt.Fprintf(t.out, "\nOutput: `%#x`\nConsumed gas: `%d`\nError: `%v`\n", output, gasUsed, err) } -func (t *mdLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { +func (t *MDLogger) CaptureEnter(_ vm.OpCode, _ common.Address, _ common.Address, _ []byte, _ uint64, _ *big.Int) { } -func (t *mdLogger) CaptureExit(output []byte, gasUsed uint64, err error) {} +func (t *MDLogger) CaptureExit(_ []byte, _ uint64, _ error) {} -func (*mdLogger) CaptureClauseStart(gasLimit uint64) {} +func (*MDLogger) CaptureClauseStart(_ uint64) {} -func (*mdLogger) CaptureClauseEnd(restGas uint64) {} +func (*MDLogger) CaptureClauseEnd(_ uint64) {} // ExecutionResult groups all structured logs emitted by the EVM // while replaying a transaction in debug mode as well as transaction diff --git a/tracers/logger/logger_json.go b/tracers/logger/logger_json.go index 792f304f3..32ef63998 100644 --- a/tracers/logger/logger_json.go +++ b/tracers/logger/logger_json.go @@ -42,7 +42,7 @@ func NewJSONLogger(cfg *Config, writer io.Writer) *JSONLogger { return l } -func (l *JSONLogger) CaptureStart(env *vm.EVM, from, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { +func (l *JSONLogger) CaptureStart(env *vm.EVM, _, _ common.Address, _ bool, _ []byte, _ uint64, _ *big.Int) { l.env = env } @@ -52,7 +52,7 @@ func (l *JSONLogger) CaptureFault(pc uint64, op vm.OpCode, gas uint64, cost uint } // CaptureState outputs state information on the logger. -func (l *JSONLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, rData []byte, depth int, err error) { +func (l *JSONLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, _ *vm.Contract, rData []byte, depth int, err error) { log := StructLog{ Pc: pc, Op: op, @@ -89,7 +89,7 @@ func (l *JSONLogger) CaptureEnd(output []byte, gasUsed uint64, err error) { l.encoder.Encode(endLog{common.Bytes2Hex(output), math.HexOrDecimal64(gasUsed), errMsg}) } -func (l *JSONLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { +func (l *JSONLogger) CaptureEnter(_ vm.OpCode, _ common.Address, _ common.Address, _ []byte, _ uint64, _ *big.Int) { } -func (l *JSONLogger) CaptureExit(output []byte, gasUsed uint64, err error) {} +func (l *JSONLogger) CaptureExit(_ []byte, _ uint64, _ error) {} diff --git a/tracers/logger/logger_test.go b/tracers/logger/logger_test.go index ebf4b8772..4dadd47ec 100644 --- a/tracers/logger/logger_test.go +++ b/tracers/logger/logger_test.go @@ -39,14 +39,14 @@ type dummyContractRef struct { func (dummyContractRef) Address() common.Address { return common.Address{} } func (dummyContractRef) Value() *big.Int { return new(big.Int) } func (dummyContractRef) SetCode(common.Hash, []byte) {} -func (d *dummyContractRef) ForEachStorage(callback func(key, value common.Hash) bool) { +func (d *dummyContractRef) ForEachStorage(_ func(key, value common.Hash) bool) { d.calledForEach = true } -func (d *dummyContractRef) SubBalance(amount *big.Int) {} -func (d *dummyContractRef) AddBalance(amount *big.Int) {} -func (d *dummyContractRef) SetBalance(*big.Int) {} -func (d *dummyContractRef) SetNonce(uint64) {} -func (d *dummyContractRef) Balance() *big.Int { return new(big.Int) } +func (d *dummyContractRef) SubBalance(_ *big.Int) {} +func (d *dummyContractRef) AddBalance(_ *big.Int) {} +func (d *dummyContractRef) SetBalance(*big.Int) {} +func (d *dummyContractRef) SetNonce(uint64) {} +func (d *dummyContractRef) Balance() *big.Int { return new(big.Int) } type dummyStatedb struct { vm.StateDB diff --git a/tracers/native/4byte.go b/tracers/native/4byte.go index b881b3e55..548667a4b 100644 --- a/tracers/native/4byte.go +++ b/tracers/native/4byte.go @@ -75,11 +75,11 @@ func (t *fourByteTracer) isPrecompiled(addr common.Address) bool { // store saves the given identifier and datasize. func (t *fourByteTracer) store(id []byte, size int) { key := bytesToHex(id) + "-" + strconv.Itoa(size) - t.ids[key] += 1 + t.ids[key]++ } // CaptureStart implements the EVMLogger interface to initialize the tracing operation. -func (t *fourByteTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { +func (t *fourByteTracer) CaptureStart(env *vm.EVM, _ common.Address, _ common.Address, _ bool, input []byte, _ uint64, _ *big.Int) { // Update list of precompiles based on current block rules := env.ChainConfig().Rules(env.Context.BlockNumber) t.activePrecompiles = vm.ActivePrecompiles(rules) @@ -91,7 +91,7 @@ func (t *fourByteTracer) CaptureStart(env *vm.EVM, from common.Address, to commo } // CaptureEnter is called when EVM enters a new scope (via call, create or selfdestruct). -func (t *fourByteTracer) CaptureEnter(op vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { +func (t *fourByteTracer) CaptureEnter(op vm.OpCode, _ common.Address, to common.Address, input []byte, _ uint64, _ *big.Int) { // Skip if tracing was interrupted if stop := t.interrupt.Load(); stop != nil && stop.(bool) { return diff --git a/tracers/native/call.go b/tracers/native/call.go index 203861dc8..110989c71 100644 --- a/tracers/native/call.go +++ b/tracers/native/call.go @@ -118,7 +118,7 @@ func newCallTracer(cfg json.RawMessage) (tracers.Tracer, error) { } // CaptureStart implements the EVMLogger interface to initialize the tracing operation. -func (t *callTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { +func (t *callTracer) CaptureStart(_ *vm.EVM, from common.Address, to common.Address, create bool, input []byte, _ uint64, value *big.Int) { toCopy := to t.callstack[0] = callFrame{ Type: vm.CALL, @@ -134,12 +134,12 @@ func (t *callTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Ad } // CaptureEnd is called after the call finishes to finalize the tracing. -func (t *callTracer) CaptureEnd(output []byte, gasUsed uint64, err error) { +func (t *callTracer) CaptureEnd(output []byte, _ uint64, err error) { t.callstack[0].processOutput(output, err) } // CaptureState implements the EVMLogger interface to trace a single step of VM execution. -func (t *callTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, rData []byte, depth int, err error) { +func (t *callTracer) CaptureState(pc uint64, op vm.OpCode, _, _ uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, rData []byte, depth int, err error) { // skip if the previous op caused an error if err != nil { return @@ -217,7 +217,7 @@ func (t *callTracer) CaptureExit(output []byte, gasUsed uint64, err error) { // pop call call := t.callstack[size-1] t.callstack = t.callstack[:size-1] - size -= 1 + size-- call.GasUsed = gasUsed call.processOutput(output, err) diff --git a/tracers/native/noop.go b/tracers/native/noop.go index 60ca8dc38..1a9c1f947 100644 --- a/tracers/native/noop.go +++ b/tracers/native/noop.go @@ -39,40 +39,40 @@ func newNoopTracer(_ json.RawMessage) (tracers.Tracer, error) { } // CaptureStart implements the EVMLogger interface to initialize the tracing operation. -func (t *noopTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { +func (t *noopTracer) CaptureStart(_ *vm.EVM, _ common.Address, _ common.Address, _ bool, _ []byte, _ uint64, _ *big.Int) { } // CaptureEnd is called after the call finishes to finalize the tracing. -func (t *noopTracer) CaptureEnd(output []byte, gasUsed uint64, err error) { +func (t *noopTracer) CaptureEnd(_ []byte, _ uint64, _ error) { } // CaptureState implements the EVMLogger interface to trace a single step of VM execution. -func (t *noopTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, rData []byte, depth int, err error) { +func (t *noopTracer) CaptureState(_ uint64, _ vm.OpCode, _, _ uint64, _ *vm.Memory, _ *vm.Stack, _ *vm.Contract, _ []byte, _ int, _ error) { } // CaptureFault implements the EVMLogger interface to trace an execution fault. -func (t *noopTracer) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, depth int, err error) { +func (t *noopTracer) CaptureFault(_ uint64, _ vm.OpCode, _, _ uint64, _ *vm.Memory, _ *vm.Stack, _ *vm.Contract, _ int, _ error) { } // CaptureEnter is called when EVM enters a new scope (via call, create or selfdestruct). -func (t *noopTracer) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { +func (t *noopTracer) CaptureEnter(_ vm.OpCode, _ common.Address, _ common.Address, _ []byte, _ uint64, _ *big.Int) { } // CaptureExit is called when EVM exits a scope, even if the scope didn't // execute any code. -func (t *noopTracer) CaptureExit(output []byte, gasUsed uint64, err error) { +func (t *noopTracer) CaptureExit(_ []byte, _ uint64, _ error) { } // CaptureClauseStart implements the Tracer interface and is invoked at the beginning of // clause processing. -func (*noopTracer) CaptureClauseStart(gasLimit uint64) {} +func (*noopTracer) CaptureClauseStart(_ uint64) {} // CaptureClauseEnd implements the Tracer interface and is invoked at the end of // clause processing. -func (*noopTracer) CaptureClauseEnd(restGas uint64) {} +func (*noopTracer) CaptureClauseEnd(_ uint64) {} // SetContext set the tracer context -func (t *noopTracer) SetContext(ctx *tracers.Context) { +func (t *noopTracer) SetContext(_ *tracers.Context) { } // GetResult returns an empty json object. @@ -81,5 +81,5 @@ func (t *noopTracer) GetResult() (json.RawMessage, error) { } // Stop terminates execution of the tracer at the first opportune moment. -func (t *noopTracer) Stop(err error) { +func (t *noopTracer) Stop(_ error) { } diff --git a/tracers/native/prestate.go b/tracers/native/prestate.go index 9f27b6231..17f808515 100644 --- a/tracers/native/prestate.go +++ b/tracers/native/prestate.go @@ -91,7 +91,7 @@ func newPrestateTracer(cfg json.RawMessage) (tracers.Tracer, error) { } // CaptureStart implements the EVMLogger interface to initialize the tracing operation. -func (t *prestateTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { +func (t *prestateTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, _ []byte, _ uint64, _ *big.Int) { t.env = env t.create = create t.to = to @@ -109,7 +109,7 @@ func (t *prestateTracer) CaptureStart(env *vm.EVM, from common.Address, to commo } // CaptureEnd is called after the call finishes to finalize the tracing. -func (t *prestateTracer) CaptureEnd(output []byte, gasUsed uint64, err error) { +func (t *prestateTracer) CaptureEnd(_ []byte, _ uint64, _ error) { if t.config.DiffMode { return } @@ -127,7 +127,7 @@ func (t *prestateTracer) CaptureClauseStart(gasLimit uint64) { t.gasLimit = gasLimit } -func (t *prestateTracer) CaptureClauseEnd(restGas uint64) { +func (t *prestateTracer) CaptureClauseEnd(_ uint64) { if !t.config.DiffMode { return } @@ -197,7 +197,7 @@ func (t *prestateTracer) CaptureClauseEnd(restGas uint64) { } // CaptureState implements the EVMLogger interface to trace a single step of VM execution. -func (t *prestateTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, rData []byte, depth int, err error) { +func (t *prestateTracer) CaptureState(_ uint64, op vm.OpCode, _, _ uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, _ []byte, _ int, err error) { if err != nil { return } diff --git a/trie/derive_root.go b/trie/derive_root.go index dec892c64..9f03b1096 100644 --- a/trie/derive_root.go +++ b/trie/derive_root.go @@ -1,5 +1,4 @@ // Copyright (c) 2018 The VeChainThor developers - // Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying // file LICENSE or diff --git a/trie/fast_node_encoder.go b/trie/fast_node_encoder.go index 42c8b61a4..f67f5b52a 100644 --- a/trie/fast_node_encoder.go +++ b/trie/fast_node_encoder.go @@ -60,7 +60,7 @@ func (n *hashNode) encodeTrailing(e *lowrlp.Encoder) { e.EncodeUint(n.seq) } -func (n *valueNode) encode(e *lowrlp.Encoder, nonCrypto bool) { +func (n *valueNode) encode(e *lowrlp.Encoder, _ bool) { e.EncodeString(n.Value) } diff --git a/trie/node.go b/trie/node.go index 1d10d25f8..77108aac3 100644 --- a/trie/node.go +++ b/trie/node.go @@ -76,8 +76,8 @@ func (n *valueNode) EncodeRLP(w io.Writer) error { return rlp.Encode(w, n.Value) } -func (n *fullNode) copy() *fullNode { copy := *n; return © } -func (n *shortNode) copy() *shortNode { copy := *n; return © } +func (n *fullNode) copy() *fullNode { cpy := *n; return &cpy } +func (n *shortNode) copy() *shortNode { cpy := *n; return &cpy } // nodeFlag contains caching-related metadata about a node. type nodeFlag struct { @@ -130,10 +130,10 @@ func (n *fullNode) fstring(ind string) string { func (n *shortNode) fstring(ind string) string { return fmt.Sprintf("{%x: %v} ", n.Key, n.Val.fstring(ind+" ")) } -func (n *hashNode) fstring(ind string) string { +func (n *hashNode) fstring(_ string) string { return fmt.Sprintf("<%v> ", n.Hash) } -func (n *valueNode) fstring(ind string) string { +func (n *valueNode) fstring(_ string) string { return fmt.Sprintf("%x ", n.Value) } @@ -254,7 +254,7 @@ func decodeShort(hash *hashNode, buf, elems []byte, trailing *trailing, cacheGen return &shortNode{key, r, flag}, nil } -func decodeFull(hash *hashNode, buf, elems []byte, trailing *trailing, cacheGen uint16) (*fullNode, error) { +func decodeFull(hash *hashNode, _, elems []byte, trailing *trailing, cacheGen uint16) (*fullNode, error) { n := &fullNode{flags: nodeFlag{hash: hash, gen: cacheGen}} for i := 0; i < 16; i++ { cld, rest, err := decodeRef(elems, trailing, cacheGen) diff --git a/trie/trie_test.go b/trie/trie_test.go index 0774de81c..1687222cc 100644 --- a/trie/trie_test.go +++ b/trie/trie_test.go @@ -674,7 +674,7 @@ type kedb struct { *ethdb.MemDatabase } -func (db *kedb) Encode(hash []byte, seq uint64, path []byte) []byte { +func (db *kedb) Encode(_ []byte, seq uint64, path []byte) []byte { var k [8]byte binary.BigEndian.PutUint64(k[:], seq) return append(k[:], path...) diff --git a/tx/receipt_test.go b/tx/receipt_test.go index 6c1dc9f0f..08948009a 100644 --- a/tx/receipt_test.go +++ b/tx/receipt_test.go @@ -12,26 +12,26 @@ import ( "github.com/stretchr/testify/assert" "github.com/vechain/thor/v2/thor" - . "github.com/vechain/thor/v2/tx" + "github.com/vechain/thor/v2/tx" ) -func getMockReceipt() Receipt { - receipt := Receipt{ +func getMockReceipt() tx.Receipt { + receipt := tx.Receipt{ GasUsed: 1000, GasPayer: thor.Address{}, Paid: big.NewInt(100), Reward: big.NewInt(50), Reverted: false, - Outputs: []*Output{}, + Outputs: []*tx.Output{}, } return receipt } func TestReceipt(t *testing.T) { - var rs Receipts + var rs tx.Receipts fmt.Println(rs.RootHash()) - var txs Transactions + var txs tx.Transactions fmt.Println(txs.RootHash()) } @@ -43,14 +43,14 @@ func TestReceiptStructure(t *testing.T) { assert.Equal(t, big.NewInt(100), receipt.Paid) assert.Equal(t, big.NewInt(50), receipt.Reward) assert.Equal(t, false, receipt.Reverted) - assert.Equal(t, []*Output{}, receipt.Outputs) + assert.Equal(t, []*tx.Output{}, receipt.Outputs) } func TestEmptyRootHash(t *testing.T) { receipt1 := getMockReceipt() receipt2 := getMockReceipt() - receipts := Receipts{ + receipts := tx.Receipts{ &receipt1, &receipt2, } diff --git a/tx/transaction_test.go b/tx/transaction_test.go index 60be5ccfe..0d364f2f4 100644 --- a/tx/transaction_test.go +++ b/tx/transaction_test.go @@ -47,7 +47,7 @@ func TestHash(t *testing.T) { func TestDependsOn(t *testing.T) { tx := GetMockTx() res := tx.DependsOn() - var expected *thor.Bytes32 = nil + var expected *thor.Bytes32 assert.Equal(t, expected, res) } @@ -87,7 +87,7 @@ func TestProvedWork(t *testing.T) { headBlockNum := uint32(20) // Mock getBlockID function - getBlockID := func(num uint32) (thor.Bytes32, error) { + getBlockID := func(_ uint32) (thor.Bytes32, error) { return thor.Bytes32{}, nil } diff --git a/txpool/tx_pool_test.go b/txpool/tx_pool_test.go index c337534d0..e843a1b7c 100644 --- a/txpool/tx_pool_test.go +++ b/txpool/tx_pool_test.go @@ -68,7 +68,7 @@ func newPoolWithParams(limit int, limitPerAccount int, BlocklistCacheFilePath st }) } -func newHttpServer() *httptest.Server { +func newHTTPServer() *httptest.Server { // Example data to be served by the mock server data := "0x25Df024637d4e56c1aE9563987Bf3e92C9f534c0\n0x25Df024637d4e56c1aE9563987Bf3e92C9f534c1\n0x865306084235bf804c8bba8a8d56890940ca8f0b" @@ -85,7 +85,7 @@ func newHttpServer() *httptest.Server { } func TestNewCloseWithServer(t *testing.T) { - server := newHttpServer() + server := newHTTPServer() defer server.Close() pool := newPoolWithParams(LIMIT, LIMIT_PER_ACCOUNT, "./", server.URL, uint64(time.Now().Unix())) diff --git a/vm/analysis.go b/vm/analysis.go index c830d9152..ed37a00d0 100644 --- a/vm/analysis.go +++ b/vm/analysis.go @@ -114,7 +114,7 @@ func codeBitmapInternal(code, bits bitvec) bitvec { switch numbits { case 1: bits.set1(pc) - pc += 1 + pc++ case 2: bits.setN(set2BitsMask, pc) pc += 2 diff --git a/vm/contracts.go b/vm/contracts.go index 8954dd58a..ac6cd3fc8 100644 --- a/vm/contracts.go +++ b/vm/contracts.go @@ -66,7 +66,7 @@ var PrecompiledContractsByzantium = map[common.Address]PrecompiledContract{ // PrecompiledContractsIstanbul contains the default set of pre-compiled Ethereum // contracts used in the Istanbul release. var PrecompiledContractsIstanbul = map[common.Address]PrecompiledContract{ - common.BytesToAddress([]byte{1}): &safe_ecrecover{}, + common.BytesToAddress([]byte{1}): &safeEcrecover{}, common.BytesToAddress([]byte{2}): &sha256hash{}, common.BytesToAddress([]byte{3}): &ripemd160hash{}, common.BytesToAddress([]byte{4}): &dataCopy{}, @@ -143,14 +143,14 @@ func (c *ecrecover) Run(input []byte) ([]byte, error) { return common.LeftPadBytes(thor.Keccak256(pubKey[1:]).Bytes()[12:], 32), nil } -// safe_ecrecover prevent touching the input buffer. -type safe_ecrecover struct{} +// safeEcrecover prevent touching the input buffer. +type safeEcrecover struct{} -func (c *safe_ecrecover) RequiredGas(input []byte) uint64 { +func (c *safeEcrecover) RequiredGas(_ []byte) uint64 { return params.EcrecoverGas } -func (c *safe_ecrecover) Run(input []byte) ([]byte, error) { +func (c *safeEcrecover) Run(input []byte) ([]byte, error) { const ecRecoverInputLength = 128 input = common.RightPadBytes(input, ecRecoverInputLength) diff --git a/vm/contracts_test.go b/vm/contracts_test.go index 5708ea4d0..9ab0a7a92 100644 --- a/vm/contracts_test.go +++ b/vm/contracts_test.go @@ -49,7 +49,7 @@ type precompiledFailureTest struct { // allPrecompiles does not map to the actual set of precompiles, as it also contains // repriced versions of precompiles at certain slots var allPrecompiles = map[common.Address]PrecompiledContract{ - common.BytesToAddress([]byte{1}): &safe_ecrecover{}, + common.BytesToAddress([]byte{1}): &safeEcrecover{}, common.BytesToAddress([]byte{2}): &sha256hash{}, common.BytesToAddress([]byte{3}): &ripemd160hash{}, common.BytesToAddress([]byte{4}): &dataCopy{}, @@ -233,16 +233,16 @@ func BenchmarkPrecompiledIdentity(bench *testing.B) { } // Tests the sample inputs from the ModExp EIP 198. -func TestPrecompiledModExp(t *testing.T) { testJson("modexp", "05", t) } -func BenchmarkPrecompiledModExp(b *testing.B) { benchJson("modexp", "05", b) } +func TestPrecompiledModExp(t *testing.T) { testJSON("modexp", "05", t) } +func BenchmarkPrecompiledModExp(b *testing.B) { benchJSON("modexp", "05", b) } // Tests the sample inputs from the elliptic curve addition EIP 213. -func TestPrecompiledBn256Add(t *testing.T) { testJson("bn256Add", "06", t) } -func BenchmarkPrecompiledBn256Add(b *testing.B) { benchJson("bn256Add", "06", b) } +func TestPrecompiledBn256Add(t *testing.T) { testJSON("bn256Add", "06", t) } +func BenchmarkPrecompiledBn256Add(b *testing.B) { benchJSON("bn256Add", "06", b) } // Tests OOG func TestPrecompiledModExpOOG(t *testing.T) { - modexpTests, err := loadJson("modexp") + modexpTests, err := loadJSON("modexp") if err != nil { t.Fatal(err) } @@ -252,15 +252,15 @@ func TestPrecompiledModExpOOG(t *testing.T) { } // Tests the sample inputs from the elliptic curve scalar multiplication EIP 213. -func TestPrecompiledBn256ScalarMul(t *testing.T) { testJson("bn256ScalarMul", "07", t) } -func BenchmarkPrecompiledBn256ScalarMul(b *testing.B) { benchJson("bn256ScalarMul", "07", b) } +func TestPrecompiledBn256ScalarMul(t *testing.T) { testJSON("bn256ScalarMul", "07", t) } +func BenchmarkPrecompiledBn256ScalarMul(b *testing.B) { benchJSON("bn256ScalarMul", "07", b) } // Tests the sample inputs from the elliptic curve pairing check EIP 197. -func TestPrecompiledBn256Pairing(t *testing.T) { testJson("bn256Pairing", "08", t) } -func BenchmarkPrecompiledBn256Pairing(b *testing.B) { benchJson("bn256Pairing", "08", b) } +func TestPrecompiledBn256Pairing(t *testing.T) { testJSON("bn256Pairing", "08", t) } +func BenchmarkPrecompiledBn256Pairing(b *testing.B) { benchJSON("bn256Pairing", "08", b) } -func TestPrecompiledBlake2F(t *testing.T) { testJson("blake2F", "09", t) } -func BenchmarkPrecompiledBlake2F(b *testing.B) { benchJson("blake2F", "09", b) } +func TestPrecompiledBlake2F(t *testing.T) { testJSON("blake2F", "09", t) } +func BenchmarkPrecompiledBlake2F(b *testing.B) { benchJSON("blake2F", "09", b) } func TestPrecompileBlake2FMalformedInput(t *testing.T) { for _, test := range blake2FMalformedInputTests { @@ -268,10 +268,10 @@ func TestPrecompileBlake2FMalformedInput(t *testing.T) { } } -func TestPrecompiledEcrecover(t *testing.T) { testJson("ecRecover", "01", t) } +func TestPrecompiledEcrecover(t *testing.T) { testJSON("ecRecover", "01", t) } -func testJson(name, addr string, t *testing.T) { - tests, err := loadJson(name) +func testJSON(name, addr string, t *testing.T) { + tests, err := loadJSON(name) if err != nil { t.Fatal(err) } @@ -280,8 +280,8 @@ func testJson(name, addr string, t *testing.T) { } } -func benchJson(name, addr string, b *testing.B) { - tests, err := loadJson(name) +func benchJSON(name, addr string, b *testing.B) { + tests, err := loadJSON(name) if err != nil { b.Fatal(err) } @@ -290,7 +290,7 @@ func benchJson(name, addr string, b *testing.B) { } } -func loadJson(name string) ([]precompiledTest, error) { +func loadJSON(name string) ([]precompiledTest, error) { data, err := os.ReadFile(fmt.Sprintf("testdata/precompiles/%v.json", name)) if err != nil { return nil, err diff --git a/vm/evm_test.go b/vm/evm_test.go index 42856dbc5..55b958ce6 100644 --- a/vm/evm_test.go +++ b/vm/evm_test.go @@ -19,20 +19,20 @@ var _ Logger = (*noopTracer)(nil) type noopTracer struct{} -func (t *noopTracer) CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { +func (t *noopTracer) CaptureStart(_ *EVM, _ common.Address, _ common.Address, _ bool, _ []byte, _ uint64, _ *big.Int) { } -func (t *noopTracer) CaptureEnd(output []byte, gasUsed uint64, err error) { +func (t *noopTracer) CaptureEnd(_ []byte, _ uint64, _ error) { } -func (t *noopTracer) CaptureState(pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, rData []byte, depth int, err error) { +func (t *noopTracer) CaptureState(_ uint64, _ OpCode, _, _ uint64, _ *Memory, _ *Stack, _ *Contract, _ []byte, _ int, _ error) { } -func (t *noopTracer) CaptureFault(pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) { +func (t *noopTracer) CaptureFault(_ uint64, _ OpCode, _, _ uint64, _ *Memory, _ *Stack, _ *Contract, _ int, _ error) { } -func (t *noopTracer) CaptureEnter(typ OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { +func (t *noopTracer) CaptureEnter(_ OpCode, _ common.Address, _ common.Address, _ []byte, _ uint64, _ *big.Int) { } -func (t *noopTracer) CaptureExit(output []byte, gasUsed uint64, err error) { +func (t *noopTracer) CaptureExit(_ []byte, _ uint64, _ error) { } -func (*noopTracer) CaptureClauseStart(gasLimit uint64) {} -func (*noopTracer) CaptureClauseEnd(restGas uint64) {} +func (*noopTracer) CaptureClauseStart(_ uint64) {} +func (*noopTracer) CaptureClauseEnd(_ uint64) {} func setupEvmTestContract(codeAddr *common.Address) (*EVM, *Contract) { statedb := NoopStateDB{} diff --git a/vm/gas_table.go b/vm/gas_table.go index 66aad61d9..67041f2f5 100644 --- a/vm/gas_table.go +++ b/vm/gas_table.go @@ -62,7 +62,7 @@ func constGasFunc(gas uint64) gasFunc { } } -func gasCallDataCopy(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasCallDataCopy(_ params.GasTable, _ *EVM, _ *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { gas, err := memoryGasCost(mem, memorySize) if err != nil { return 0, err @@ -88,7 +88,7 @@ func gasCallDataCopy(gt params.GasTable, evm *EVM, contract *Contract, stack *St return gas, nil } -func gasReturnDataCopy(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasReturnDataCopy(_ params.GasTable, _ *EVM, _ *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { gas, err := memoryGasCost(mem, memorySize) if err != nil { return 0, err @@ -114,7 +114,7 @@ func gasReturnDataCopy(gt params.GasTable, evm *EVM, contract *Contract, stack * return gas, nil } -func gasSStore(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasSStore(_ params.GasTable, evm *EVM, contract *Contract, stack *Stack, _ *Memory, _ uint64) (uint64, error) { var ( y, x = stack.Back(1), stack.Back(0) val = evm.StateDB.GetState(contract.Address(), x.Bytes32()) @@ -166,7 +166,7 @@ func makeGasLog(n uint64) gasFunc { } } -func gasSha3(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasSha3(_ params.GasTable, _ *EVM, _ *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { var overflow bool gas, err := memoryGasCost(mem, memorySize) if err != nil { @@ -190,7 +190,7 @@ func gasSha3(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem return gas, nil } -func gasCodeCopy(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasCodeCopy(_ params.GasTable, _ *EVM, _ *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { gas, err := memoryGasCost(mem, memorySize) if err != nil { return 0, err @@ -214,7 +214,7 @@ func gasCodeCopy(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, return gas, nil } -func gasExtCodeCopy(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasExtCodeCopy(gt params.GasTable, _ *EVM, _ *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { gas, err := memoryGasCost(mem, memorySize) if err != nil { return 0, err @@ -240,11 +240,11 @@ func gasExtCodeCopy(gt params.GasTable, evm *EVM, contract *Contract, stack *Sta return gas, nil } -func gasExtCodeHash(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasExtCodeHash(gt params.GasTable, _ *EVM, _ *Contract, _ *Stack, _ *Memory, _ uint64) (uint64, error) { return gt.ExtcodeHash, nil } -func gasMLoad(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasMLoad(_ params.GasTable, _ *EVM, _ *Contract, _ *Stack, mem *Memory, memorySize uint64) (uint64, error) { var overflow bool gas, err := memoryGasCost(mem, memorySize) if err != nil { @@ -256,7 +256,7 @@ func gasMLoad(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, me return gas, nil } -func gasMStore8(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasMStore8(_ params.GasTable, _ *EVM, _ *Contract, _ *Stack, mem *Memory, memorySize uint64) (uint64, error) { var overflow bool gas, err := memoryGasCost(mem, memorySize) if err != nil { @@ -268,7 +268,7 @@ func gasMStore8(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, return gas, nil } -func gasMStore(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasMStore(_ params.GasTable, _ *EVM, _ *Contract, _ *Stack, mem *Memory, memorySize uint64) (uint64, error) { var overflow bool gas, err := memoryGasCost(mem, memorySize) if err != nil { @@ -280,7 +280,7 @@ func gasMStore(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, m return gas, nil } -func gasCreate(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasCreate(_ params.GasTable, _ *EVM, _ *Contract, _ *Stack, mem *Memory, memorySize uint64) (uint64, error) { var overflow bool gas, err := memoryGasCost(mem, memorySize) if err != nil { @@ -292,7 +292,7 @@ func gasCreate(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, m return gas, nil } -func gasCreate2(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasCreate2(_ params.GasTable, _ *EVM, _ *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { var overflow bool gas, err := memoryGasCost(mem, memorySize) if err != nil { @@ -315,19 +315,19 @@ func gasCreate2(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, return gas, nil } -func gasBalance(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasBalance(gt params.GasTable, _ *EVM, _ *Contract, _ *Stack, _ *Memory, _ uint64) (uint64, error) { return gt.Balance, nil } -func gasExtCodeSize(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasExtCodeSize(gt params.GasTable, _ *EVM, _ *Contract, _ *Stack, _ *Memory, _ uint64) (uint64, error) { return gt.ExtcodeSize, nil } -func gasSLoad(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasSLoad(gt params.GasTable, _ *EVM, _ *Contract, _ *Stack, _ *Memory, _ uint64) (uint64, error) { return gt.SLoad, nil } -func gasExp(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasExp(gt params.GasTable, _ *EVM, _ *Contract, stack *Stack, _ *Memory, _ uint64) (uint64, error) { expByteLen := uint64((stack.data[stack.len()-2].BitLen() + 7) / 8) var ( @@ -400,15 +400,15 @@ func gasCallCode(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, return gas, nil } -func gasReturn(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasReturn(_ params.GasTable, _ *EVM, _ *Contract, _ *Stack, mem *Memory, memorySize uint64) (uint64, error) { return memoryGasCost(mem, memorySize) } -func gasRevert(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasRevert(_ params.GasTable, _ *EVM, _ *Contract, _ *Stack, mem *Memory, memorySize uint64) (uint64, error) { return memoryGasCost(mem, memorySize) } -func gasSuicide(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { +func gasSuicide(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, _ *Memory, _ uint64) (uint64, error) { var gas uint64 // EIP150 homestead gas reprice fork: if evm.ChainConfig().IsEIP150(evm.BlockNumber) { diff --git a/vm/gas_table_test.go b/vm/gas_table_test.go index d7e2c5773..860569927 100644 --- a/vm/gas_table_test.go +++ b/vm/gas_table_test.go @@ -29,7 +29,7 @@ import ( "github.com/stretchr/testify/assert" ) -func newContractAddress(evm *EVM, counter uint32) common.Address { +func newContractAddress(_ *EVM, _ uint32) common.Address { return common.HexToAddress("0x012345657ABC") } diff --git a/vm/instructions.go b/vm/instructions.go index 75cedb96b..ac475f9d6 100644 --- a/vm/instructions.go +++ b/vm/instructions.go @@ -33,67 +33,67 @@ var ( errMaxCodeSizeExceeded = errors.New("evm: max code size exceeded") ) -func opAdd(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opAdd(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() y.Add(x, y) return nil, nil } -func opSub(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSub(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() y.Sub(x, y) return nil, nil } -func opMul(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opMul(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() y.Mul(x, y) return nil, nil } -func opDiv(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opDiv(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() y.Div(x, y) return nil, nil } -func opSdiv(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSdiv(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() y.SDiv(x, y) return nil, nil } -func opMod(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opMod(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() y.Mod(x, y) return nil, nil } -func opSmod(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSmod(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() y.SMod(x, y) return nil, nil } -func opExp(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opExp(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { base, exponent := stack.popptr(), stack.peek() exponent.Exp(base, exponent) return nil, nil } -func opSignExtend(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSignExtend(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { back, num := stack.popptr(), stack.peek() num.ExtendSign(num, back) return nil, nil } -func opNot(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opNot(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x := stack.peek() x.Not(x) return nil, nil } -func opLt(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opLt(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() if x.Lt(y) { y.SetOne() @@ -103,7 +103,7 @@ func opLt(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack return nil, nil } -func opGt(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opGt(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() if x.Gt(y) { y.SetOne() @@ -113,7 +113,7 @@ func opGt(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack return nil, nil } -func opSlt(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSlt(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() if x.Slt(y) { y.SetOne() @@ -123,7 +123,7 @@ func opSlt(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stac return nil, nil } -func opSgt(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSgt(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() if x.Sgt(y) { y.SetOne() @@ -133,7 +133,7 @@ func opSgt(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stac return nil, nil } -func opEq(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opEq(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() if x.Eq(y) { y.SetOne() @@ -143,7 +143,7 @@ func opEq(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack return nil, nil } -func opIszero(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opIszero(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x := stack.peek() if x.IsZero() { x.SetOne() @@ -153,31 +153,31 @@ func opIszero(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *S return nil, nil } -func opAnd(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opAnd(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() y.And(x, y) return nil, nil } -func opOr(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opOr(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() y.Or(x, y) return nil, nil } -func opXor(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opXor(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y := stack.popptr(), stack.peek() y.Xor(x, y) return nil, nil } -func opByte(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opByte(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { th, val := stack.popptr(), stack.peek() val.Byte(th) return nil, nil } -func opAddmod(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opAddmod(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y, z := stack.popptr(), stack.popptr(), stack.peek() if z.IsZero() { z.Clear() @@ -187,7 +187,7 @@ func opAddmod(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *S return nil, nil } -func opMulmod(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opMulmod(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { x, y, z := stack.popptr(), stack.popptr(), stack.peek() z.MulMod(x, y, z) return nil, nil @@ -196,7 +196,7 @@ func opMulmod(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *S // opSHL implements Shift Left // The SHL instruction (shift left) pops 2 values from the stack, first arg1 and then arg2, // and pushes on the stack arg2 shifted to the left by arg1 number of bits. -func opSHL(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSHL(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { // Note, second operand is left in the stack; accumulate result into it, and no need to push it afterwards shift, value := stack.popptr(), stack.peek() if shift.LtUint64(256) { @@ -210,7 +210,7 @@ func opSHL(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stac // opSHR implements Logical Shift Right // The SHR instruction (logical shift right) pops 2 values from the stack, first arg1 and then arg2, // and pushes on the stack arg2 shifted to the right by arg1 number of bits with zero fill. -func opSHR(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSHR(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { // Note, second operand is left in the stack; accumulate result into it, and no need to push it afterwards shift, value := stack.popptr(), stack.peek() if shift.LtUint64(256) { @@ -224,7 +224,7 @@ func opSHR(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stac // opSAR implements Arithmetic Shift Right // The SAR instruction (arithmetic shift right) pops 2 values from the stack, first arg1 and then arg2, // and pushes on the stack arg2 shifted to the right by arg1 number of bits with sign extension. -func opSAR(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSAR(_ *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { // Note, S256 returns (potentially) a new bigint, so we're popping, not peeking this one shift, value := stack.popptr(), stack.peek() if shift.GtUint64(256) { @@ -241,7 +241,7 @@ func opSAR(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stac return nil, nil } -func opSha3(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSha3(_ *uint64, evm *EVM, _ *Contract, memory *Memory, stack *Stack) ([]byte, error) { offset, size := stack.popptr(), stack.peek() data := memory.GetPtr(int64(offset.Uint64()), int64(size.Uint64())) @@ -254,35 +254,35 @@ func opSha3(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Sta return nil, nil } -func opAddress(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opAddress(_ *uint64, _ *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { stack.push(new(uint256.Int).SetBytes(contract.Address().Bytes())) return nil, nil } -func opBalance(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opBalance(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { slot := stack.peek() address := common.Address(slot.Bytes20()) slot.SetFromBig(evm.StateDB.GetBalance(address)) return nil, nil } -func opOrigin(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opOrigin(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { stack.push(new(uint256.Int).SetBytes(evm.Origin.Bytes())) return nil, nil } -func opCaller(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opCaller(_ *uint64, _ *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { stack.push(new(uint256.Int).SetBytes(contract.Caller().Bytes())) return nil, nil } -func opCallValue(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opCallValue(_ *uint64, _ *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { v, _ := uint256.FromBig(contract.value) stack.push(v) return nil, nil } -func opCallDataLoad(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opCallDataLoad(_ *uint64, _ *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { x := stack.peek() if offset, overflow := x.Uint64WithOverflow(); !overflow { data := getData(contract.Input, offset, 32) @@ -293,12 +293,12 @@ func opCallDataLoad(pc *uint64, evm *EVM, contract *Contract, memory *Memory, st return nil, nil } -func opCallDataSize(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opCallDataSize(_ *uint64, _ *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { stack.push(uint256.NewInt(uint64(len(contract.Input)))) return nil, nil } -func opCallDataCopy(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opCallDataCopy(_ *uint64, _ *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { var ( memOffset = stack.popptr() dataOffset = stack.popptr() @@ -315,12 +315,12 @@ func opCallDataCopy(pc *uint64, evm *EVM, contract *Contract, memory *Memory, st return nil, nil } -func opReturnDataSize(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opReturnDataSize(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { stack.push(uint256.NewInt(uint64(len(evm.interpreter.returnData)))) return nil, nil } -func opReturnDataCopy(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opReturnDataCopy(_ *uint64, evm *EVM, _ *Contract, memory *Memory, stack *Stack) ([]byte, error) { var ( memOffset = stack.popptr() dataOffset = stack.popptr() @@ -341,19 +341,19 @@ func opReturnDataCopy(pc *uint64, evm *EVM, contract *Contract, memory *Memory, return nil, nil } -func opExtCodeSize(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opExtCodeSize(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { slot := stack.peek() slot.SetUint64(uint64(evm.StateDB.GetCodeSize(slot.Bytes20()))) return nil, nil } -func opCodeSize(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opCodeSize(_ *uint64, _ *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { l := uint256.NewInt(uint64(len(contract.Code))) stack.push(l) return nil, nil } -func opCodeCopy(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opCodeCopy(_ *uint64, _ *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { var ( memOffset = stack.popptr() codeOffset = stack.popptr() @@ -368,7 +368,7 @@ func opCodeCopy(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack return nil, nil } -func opExtCodeCopy(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opExtCodeCopy(_ *uint64, evm *EVM, _ *Contract, memory *Memory, stack *Stack) ([]byte, error) { var ( a = stack.popptr() memOffset = stack.popptr() @@ -418,7 +418,7 @@ func opExtCodeCopy(pc *uint64, evm *EVM, contract *Contract, memory *Memory, sta // (6) Caller tries to get the code hash for an account which is marked as deleted, // // this account should be regarded as a non-existent account and zero should be returned. -func opExtCodeHash(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opExtCodeHash(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { slot := stack.peek() address := common.Address(slot.Bytes20()) if evm.StateDB.Empty(address) { @@ -431,13 +431,13 @@ func opExtCodeHash(pc *uint64, evm *EVM, contract *Contract, memory *Memory, sta return nil, nil } -func opGasprice(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opGasprice(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { v, _ := uint256.FromBig(evm.GasPrice) stack.push(v) return nil, nil } -func opBlockhash(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opBlockhash(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { num := stack.peek() num64, overflow := num.Uint64WithOverflow() if overflow { @@ -459,24 +459,24 @@ func opBlockhash(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack return nil, nil } -func opCoinbase(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opCoinbase(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { stack.push(new(uint256.Int).SetBytes(evm.Context.Coinbase.Bytes())) return nil, nil } -func opTimestamp(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opTimestamp(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { v, _ := uint256.FromBig(evm.Context.Time) stack.push(v) return nil, nil } -func opNumber(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opNumber(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { v, _ := uint256.FromBig(evm.Context.BlockNumber) stack.push(v) return nil, nil } -func opDifficulty(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opDifficulty(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { v, _ := uint256.FromBig(evm.Context.Difficulty) stack.push(v) return nil, nil @@ -487,32 +487,32 @@ func opGasLimit(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack return nil, nil } -func opPop(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opPop(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { stack.pop() return nil, nil } -func opMload(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opMload(_ *uint64, _ *EVM, _ *Contract, memory *Memory, stack *Stack) ([]byte, error) { v := stack.peek() offset := int64(v.Uint64()) v.SetBytes(memory.GetPtr(offset, 32)) return nil, nil } -func opMstore(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opMstore(_ *uint64, _ *EVM, _ *Contract, memory *Memory, stack *Stack) ([]byte, error) { // pop value of the stack mStart, val := stack.popptr(), stack.popptr() memory.Set32(mStart.Uint64(), val) return nil, nil } -func opMstore8(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opMstore8(_ *uint64, _ *EVM, _ *Contract, memory *Memory, stack *Stack) ([]byte, error) { off, val := stack.popptr(), stack.popptr() memory.store[off.Uint64()] = byte(val.Uint64()) return nil, nil } -func opSload(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSload(_ *uint64, evm *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { loc := stack.peek() hash := common.Hash(loc.Bytes32()) val := evm.StateDB.GetState(contract.Address(), hash) @@ -520,7 +520,7 @@ func opSload(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *St return nil, nil } -func opSstore(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSstore(_ *uint64, evm *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { loc := stack.popptr() val := stack.popptr() evm.StateDB.SetState(contract.Address(), @@ -528,7 +528,7 @@ func opSstore(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *S return nil, nil } -func opJump(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opJump(pc *uint64, _ *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { pos := stack.popptr() if !contract.validJumpdest(pos) { nop := contract.GetOp(pos.Uint64()) @@ -538,7 +538,7 @@ func opJump(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Sta return nil, nil } -func opJumpi(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opJumpi(pc *uint64, _ *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { pos, cond := stack.popptr(), stack.popptr() if !cond.IsZero() { if !contract.validJumpdest(pos) { @@ -552,11 +552,11 @@ func opJumpi(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *St return nil, nil } -func opJumpdest(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opJumpdest(_ *uint64, _ *EVM, _ *Contract, _ *Memory, _ *Stack) ([]byte, error) { return nil, nil } -func opPc(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opPc(pc *uint64, _ *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { stack.push(uint256.NewInt(*pc)) return nil, nil } @@ -566,12 +566,12 @@ func opMsize(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *St return nil, nil } -func opGas(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opGas(_ *uint64, _ *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { stack.push(uint256.NewInt(contract.Gas)) return nil, nil } -func opCreate(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opCreate(_ *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { var ( value = stack.popptr() offset, size = stack.popptr().Uint64(), stack.popptr().Uint64() @@ -610,7 +610,7 @@ func opCreate(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *S return nil, nil } -func opCreate2(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opCreate2(_ *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { var ( endowment = stack.popptr() offset, size = stack.popptr().Uint64(), stack.popptr().Uint64() @@ -643,7 +643,7 @@ func opCreate2(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack * return nil, nil } -func opCall(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opCall(_ *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { // Pop gas. The actual gas in interpreter.evm.callGasTemp. stack.pop() gas := evm.callGasTemp @@ -677,7 +677,7 @@ func opCall(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Sta return ret, nil } -func opCallCode(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opCallCode(_ *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { // Pop gas. The actual gas is in interpreter.evm.callGasTemp. stack.pop() gas := evm.callGasTemp @@ -709,7 +709,7 @@ func opCallCode(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack return ret, nil } -func opDelegateCall(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opDelegateCall(_ *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { // Pop gas. The actual gas is in interpreter.evm.callGasTemp. stack.pop() gas := evm.callGasTemp @@ -734,7 +734,7 @@ func opDelegateCall(pc *uint64, evm *EVM, contract *Contract, memory *Memory, st return ret, nil } -func opStaticCall(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opStaticCall(_ *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { // We use it as a temporary value stack.pop() gas := evm.callGasTemp @@ -759,24 +759,24 @@ func opStaticCall(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stac return ret, nil } -func opReturn(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opReturn(_ *uint64, _ *EVM, _ *Contract, memory *Memory, stack *Stack) ([]byte, error) { offset, size := stack.popptr(), stack.popptr() ret := memory.GetPtr(int64(offset.Uint64()), int64(size.Uint64())) return ret, nil } -func opRevert(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opRevert(_ *uint64, _ *EVM, _ *Contract, memory *Memory, stack *Stack) ([]byte, error) { offset, size := stack.popptr(), stack.popptr() ret := memory.GetPtr(int64(offset.Uint64()), int64(size.Uint64())) return ret, nil } -func opStop(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opStop(_ *uint64, _ *EVM, _ *Contract, _ *Memory, _ *Stack) ([]byte, error) { return nil, nil } -func opSuicide(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSuicide(_ *uint64, evm *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { receiver := stack.popptr().Bytes20() if evm.vmConfig.Tracer != nil { @@ -795,13 +795,13 @@ func opSuicide(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack * } // opChainID implements CHAINID opcode -func opChainID(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { - chainId, _ := uint256.FromBig(evm.chainConfig.ChainID) - stack.push(chainId) +func opChainID(_ *uint64, evm *EVM, _ *Contract, _ *Memory, stack *Stack) ([]byte, error) { + chainID, _ := uint256.FromBig(evm.chainConfig.ChainID) + stack.push(chainID) return nil, nil } -func opSelfBalance(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opSelfBalance(_ *uint64, evm *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { balance, _ := uint256.FromBig(evm.StateDB.GetBalance(contract.Address())) stack.push(balance) return nil, nil @@ -834,12 +834,12 @@ func makeLog(size int) executionFunc { } // opPush1 is a specialized version of pushN -func opPush1(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { +func opPush1(pc *uint64, _ *EVM, contract *Contract, _ *Memory, stack *Stack) ([]byte, error) { var ( codeLen = uint64(len(contract.Code)) integer = new(uint256.Int) ) - *pc += 1 + *pc++ if *pc < codeLen { stack.push(integer.SetUint64(uint64(contract.Code[*pc]))) } else { @@ -882,7 +882,7 @@ func makeDup(size int64) executionFunc { // make swap instruction function func makeSwap(size int64) executionFunc { // switch n + 1 otherwise n would be swapped with n - size += 1 + size++ return func(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { stack.swap(int(size)) return nil, nil diff --git a/vm/noop.go b/vm/noop.go index b71ead0d7..29e9baf1c 100644 --- a/vm/noop.go +++ b/vm/noop.go @@ -23,23 +23,23 @@ import ( "github.com/ethereum/go-ethereum/core/types" ) -func NoopCanTransfer(db StateDB, from common.Address, balance *big.Int) bool { +func NoopCanTransfer(_ StateDB, _ common.Address, _ *big.Int) bool { return true } -func NoopTransfer(db StateDB, from, to common.Address, amount *big.Int) {} +func NoopTransfer(_ StateDB, _, _ common.Address, _ *big.Int) {} type NoopEVMCallContext struct{} -func (NoopEVMCallContext) Call(caller ContractRef, addr common.Address, data []byte, gas, value *big.Int) ([]byte, error) { +func (NoopEVMCallContext) Call(_ ContractRef, _ common.Address, _ []byte, _, _ *big.Int) ([]byte, error) { return nil, nil } -func (NoopEVMCallContext) CallCode(caller ContractRef, addr common.Address, data []byte, gas, value *big.Int) ([]byte, error) { +func (NoopEVMCallContext) CallCode(_ ContractRef, _ common.Address, _ []byte, _, _ *big.Int) ([]byte, error) { return nil, nil } -func (NoopEVMCallContext) Create(caller ContractRef, data []byte, gas, value *big.Int) ([]byte, common.Address, error) { +func (NoopEVMCallContext) Create(_ ContractRef, _ []byte, _, _ *big.Int) ([]byte, common.Address, error) { return nil, common.Address{}, nil } -func (NoopEVMCallContext) DelegateCall(me ContractRef, addr common.Address, data []byte, gas *big.Int) ([]byte, error) { +func (NoopEVMCallContext) DelegateCall(_ ContractRef, _ common.Address, _ []byte, _ *big.Int) ([]byte, error) { return nil, nil } diff --git a/vrf/vrf.go b/vrf/vrf.go index 159e700df..c77f971c8 100644 --- a/vrf/vrf.go +++ b/vrf/vrf.go @@ -21,7 +21,7 @@ var vrf = ecvrf.New(&ecvrf.Config{ SuiteString: 0xfe, Cofactor: 0x01, NewHasher: sha256.New, - Decompress: func(c elliptic.Curve, pk []byte) (x, y *big.Int) { + Decompress: func(_ elliptic.Curve, pk []byte) (x, y *big.Int) { return secp256k1.DecompressPubkey(pk) }, })