From d118254b78c0ad0d0bc8814aab482246e012dc96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Negovanovi=C4=87?= Date: Tue, 8 Aug 2023 07:52:21 +0200 Subject: [PATCH 1/6] Simplify and use os.ReadFile instead of ioutil.ReadFile --- cmd/abigen/abigen.go | 7 +++---- structs_encoding_test.go | 4 ++-- testutil/mock.go | 4 +--- wallet/wallet_json.go | 4 ++-- wallet/wallet_json_test.go | 4 ++-- 5 files changed, 10 insertions(+), 13 deletions(-) diff --git a/cmd/abigen/abigen.go b/cmd/abigen/abigen.go index 58e8bbac..3de851de 100644 --- a/cmd/abigen/abigen.go +++ b/cmd/abigen/abigen.go @@ -5,7 +5,6 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io/ioutil" "os" "strings" @@ -117,7 +116,7 @@ func processAbi(sources []string, config *config) (map[string]*compiler.Artifact artifacts := map[string]*compiler.Artifact{} for _, abiPath := range sources { - content, err := ioutil.ReadFile(abiPath) + content, err := os.ReadFile(abiPath) if err != nil { return nil, fmt.Errorf("failed to read abi file (%s): %v", abiPath, err) } @@ -128,7 +127,7 @@ func processAbi(sources []string, config *config) (map[string]*compiler.Artifact name = strings.TrimSuffix(name, filepath.Ext(name)) binPath := filepath.Join(path, name+".bin") - bin, err := ioutil.ReadFile(binPath) + bin, err := os.ReadFile(binPath) if err != nil { // bin not found bin = []byte{} @@ -150,7 +149,7 @@ func processJson(sources []string) (map[string]*compiler.Artifact, error) { artifacts := map[string]*compiler.Artifact{} for _, jsonPath := range sources { - content, err := ioutil.ReadFile(jsonPath) + content, err := os.ReadFile(jsonPath) if err != nil { return nil, fmt.Errorf("failed to read abi file (%s): %v", jsonPath, err) } diff --git a/structs_encoding_test.go b/structs_encoding_test.go index 61ceff55..73fb2077 100644 --- a/structs_encoding_test.go +++ b/structs_encoding_test.go @@ -3,7 +3,7 @@ package ethgo import ( "bytes" "encoding/json" - "io/ioutil" + "os" "path/filepath" "testing" @@ -66,7 +66,7 @@ func readTestsuite(t *testing.T, pattern string) (res []*testFile) { t.Fatal("no test files found") } for _, f := range files { - data, err := ioutil.ReadFile(f) + data, err := os.ReadFile(f) if err != nil { t.Fatal(err) } diff --git a/testutil/mock.go b/testutil/mock.go index e534500a..1161d6f4 100644 --- a/testutil/mock.go +++ b/testutil/mock.go @@ -217,9 +217,7 @@ type MockBlock struct { } func mustDecodeHash(str string) []byte { - if strings.HasPrefix(str, "0x") { - str = str[2:] - } + str = strings.TrimPrefix(str, "0x") if len(str)%2 == 1 { str = str + "0" } diff --git a/wallet/wallet_json.go b/wallet/wallet_json.go index 6b6a19eb..3cff6cca 100644 --- a/wallet/wallet_json.go +++ b/wallet/wallet_json.go @@ -1,13 +1,13 @@ package wallet import ( - "io/ioutil" + "os" "github.com/umbracle/ethgo/keystore" ) func NewJSONWalletFromFile(path string, password string) (*Key, error) { - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) if err != nil { return nil, err } diff --git a/wallet/wallet_json_test.go b/wallet/wallet_json_test.go index a5bbbb2e..bb2a93d3 100644 --- a/wallet/wallet_json_test.go +++ b/wallet/wallet_json_test.go @@ -2,14 +2,14 @@ package wallet import ( "encoding/json" - "io/ioutil" + "os" "testing" "github.com/stretchr/testify/assert" ) func TestWallet_JSON(t *testing.T) { - raw, err := ioutil.ReadFile("./fixtures/wallet_json.json") + raw, err := os.ReadFile("./fixtures/wallet_json.json") assert.NoError(t, err) var cases []struct { From f00f0bffbbda953f095d20fefdd1cd606e551ac3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Negovanovi=C4=87?= Date: Tue, 8 Aug 2023 09:42:33 +0200 Subject: [PATCH 2/6] Error checkings and other misc fixes --- abi/decode_test.go | 4 +++- abi/encode.go | 4 +--- abi/encoding_test.go | 7 +++++-- abi/testing.go | 2 -- abi/type.go | 8 ++++++-- blocktracker/blocktracker_test.go | 8 ++++---- jsonrpc/subscribe_test.go | 6 +++--- keystore/utils.go | 2 +- tracker/store/inmem/inmem_store.go | 4 +--- tracker/tracker.go | 6 +++--- tracker/tracker_test.go | 26 ++++++++++++++++---------- 11 files changed, 43 insertions(+), 34 deletions(-) diff --git a/abi/decode_test.go b/abi/decode_test.go index 9c3d74b7..7504950b 100644 --- a/abi/decode_test.go +++ b/abi/decode_test.go @@ -8,7 +8,9 @@ import ( func TestDecode_BytesBound(t *testing.T) { typ := MustNewType("tuple(string)") - decodeTuple(typ, nil) // it should not panic + require.NotPanics(t, func() { + _, _, _ = decodeTuple(typ, nil) // it should not panic + }) } func TestDecode_DynamicLengthOutOfBounds(t *testing.T) { diff --git a/abi/encode.go b/abi/encode.go index 41afb960..d0aecfb2 100644 --- a/abi/encode.go +++ b/abi/encode.go @@ -352,9 +352,7 @@ func encodeHex(b []byte) string { } func decodeHex(str string) ([]byte, error) { - if strings.HasPrefix(str, "0x") { - str = str[2:] - } + str = strings.TrimPrefix(str, "0x") buf, err := hex.DecodeString(str) if err != nil { return nil, fmt.Errorf("could not decode hex: %v", err) diff --git a/abi/encoding_test.go b/abi/encoding_test.go index df0d348c..06726106 100644 --- a/abi/encoding_test.go +++ b/abi/encoding_test.go @@ -317,7 +317,8 @@ func TestEncoding(t *testing.T) { server := testutil.NewTestServer(t) for _, c := range cases { - t.Run("", func(t *testing.T) { + c := c + t.Run(fmt.Sprintf("Encoding type %s", c.Type), func(t *testing.T) { t.Parallel() tt, err := NewType(c.Type) @@ -644,7 +645,9 @@ func testDecodePanic(tt *Type, input interface{}) error { copy(buf, res1) buf[i] = 0xff - Decode(tt, buf) + if _, err = Decode(tt, buf); err != nil { + return err + } } return nil diff --git a/abi/testing.go b/abi/testing.go index aafca72e..89b79cc9 100644 --- a/abi/testing.go +++ b/abi/testing.go @@ -162,8 +162,6 @@ func generateRandomType(t *Type) interface{} { } } -const hexLetters = "0123456789abcdef" - const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" func randString(n int, dict string) string { diff --git a/abi/type.go b/abi/type.go index a7189bd1..3e176645 100644 --- a/abi/type.go +++ b/abi/type.go @@ -292,7 +292,9 @@ func NewTypeFromArgument(arg *ArgumentStr) (*Type, error) { } // fill-in the `internalType` field into the type elems - fillIn(typ, arg) + if err = fillIn(typ, arg); err != nil { + return nil, err + } return typ, nil } @@ -326,7 +328,9 @@ func fillIn(typ *Type, arg *ArgumentStr) error { } for indx, i := range arg.Components { - fillIn(typ.tuple[indx].Elem, i) + if err := fillIn(typ.tuple[indx].Elem, i); err != nil { + return err + } } return nil diff --git a/blocktracker/blocktracker_test.go b/blocktracker/blocktracker_test.go index bb468e75..bc4dcf32 100644 --- a/blocktracker/blocktracker_test.go +++ b/blocktracker/blocktracker_test.go @@ -43,10 +43,10 @@ func testListener(t *testing.T, server *testutil.TestServer, tracker BlockTracke } } - server.ProcessBlock() + assert.NoError(t, server.ProcessBlock()) recv() - server.ProcessBlock() + assert.NoError(t, server.ProcessBlock()) recv() } @@ -91,7 +91,7 @@ func TestBlockTracker_Lifecycle(t *testing.T) { // try to mine a block at least every 1 second go func() { for i := 0; i < 10; i++ { - s.ProcessBlock() + assert.NoError(t, s.ProcessBlock()) time.After(1 * time.Second) } }() @@ -345,7 +345,7 @@ func TestBlockTracker_Events(t *testing.T) { // build past block history for _, b := range c.History.ToBlocks() { - tt.AddBlockLocked(b) + assert.NoError(t, tt.AddBlockLocked(b)) } sub := tt.Subscribe() diff --git a/jsonrpc/subscribe_test.go b/jsonrpc/subscribe_test.go index e84c83f6..caa91b18 100644 --- a/jsonrpc/subscribe_test.go +++ b/jsonrpc/subscribe_test.go @@ -53,15 +53,15 @@ func TestSubscribeNewHead(t *testing.T) { } } - s.ProcessBlock() + assert.NoError(t, s.ProcessBlock()) recv(true) - s.ProcessBlock() + assert.NoError(t, s.ProcessBlock()) recv(true) assert.NoError(t, cancel()) - s.ProcessBlock() + assert.NoError(t, s.ProcessBlock()) recv(false) // subscription already closed diff --git a/keystore/utils.go b/keystore/utils.go index 5d9d7e89..926c8064 100644 --- a/keystore/utils.go +++ b/keystore/utils.go @@ -16,7 +16,7 @@ import ( func getRand(size int) []byte { buf := make([]byte, size) - rand.Read(buf) + rand.Read(buf) //nolint:errcheck return buf } diff --git a/tracker/store/inmem/inmem_store.go b/tracker/store/inmem/inmem_store.go index 5baef7a6..eb3b1b9e 100644 --- a/tracker/store/inmem/inmem_store.go +++ b/tracker/store/inmem/inmem_store.go @@ -96,9 +96,7 @@ func (e *Entry) Logs() []*ethgo.Log { func (e *Entry) StoreLogs(logs []*ethgo.Log) error { e.l.Lock() defer e.l.Unlock() - for _, log := range logs { - e.logs = append(e.logs, log) - } + e.logs = append(e.logs, logs...) return nil } diff --git a/tracker/tracker.go b/tracker/tracker.go index 11902bf3..08bdba6b 100644 --- a/tracker/tracker.go +++ b/tracker/tracker.go @@ -276,8 +276,8 @@ func (t *Tracker) IsSynced() bool { } // Wait waits the filter to finish -func (t *Tracker) Wait() { - t.WaitDuration(0) +func (t *Tracker) Wait() error { + return t.WaitDuration(0) } // WaitDuration waits for the filter to finish up to duration @@ -679,7 +679,7 @@ func (t *Tracker) syncImpl(ctx context.Context) error { } t.emitLogs(EventDel, logs) - last, err = t.getBlockByNumber(ancestor) + _, err = t.getBlockByNumber(ancestor) if err != nil { return err } diff --git a/tracker/tracker_test.go b/tracker/tracker_test.go index e9638ae5..5a4b20a0 100644 --- a/tracker/tracker_test.go +++ b/tracker/tracker_test.go @@ -56,7 +56,10 @@ func TestPolling(t *testing.T) { // send 5 txns for i := 0; i < 5; i++ { - s.TxnTo(addr0, "setA1") + receipt, err := s.TxnTo(addr0, "setA1") + require.NoError(t, err) + require.NotNil(t, receipt) + require.Equal(t, uint64(1), receipt.Status) } tt, err := NewTracker(client.Eth()) @@ -255,7 +258,9 @@ func testSyncerReconcile(t *testing.T, iniLen, forkNum, endLen int) { panic(err) } }() - tt0.WaitDuration(2 * time.Second) + + err = tt0.WaitDuration(2 * time.Second) + assert.NoError(t, err) // create a fork at 'forkNum' and continue to 'endLen' l1 := testutil.MockList{} @@ -286,7 +291,8 @@ func testSyncerReconcile(t *testing.T, iniLen, forkNum, endLen int) { panic(err) } }() - tt1.WaitDuration(2 * time.Second) + err = tt1.WaitDuration(2 * time.Second) + assert.NoError(t, err) logs := tt1.entry.(*inmem.Entry).Logs() @@ -653,18 +659,18 @@ func TestTrackerReconcile(t *testing.T) { // build past block history for _, b := range c.History.ToBlocks() { - tt.blockTracker.AddBlockLocked(b) + err = tt.blockTracker.AddBlockLocked(b) + require.NoError(t, err) } // add the history to the store for _, b := range c.History { - tt.entry.StoreLogs(b.GetLogs()) + err = tt.entry.StoreLogs(b.GetLogs()) + require.NoError(t, err) } for _, b := range c.Reconcile { aux, err := tt.blockTracker.HandleBlockEvent(b.block.Block()) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if aux == nil { continue } @@ -716,7 +722,7 @@ func TestTrackerReconcile(t *testing.T) { type mockClientWithLimit struct { limit uint64 - testutil.MockClient + *testutil.MockClient } func (m *mockClientWithLimit) GetLogs(filter *ethgo.LogFilter) ([]*ethgo.Log, error) { @@ -757,7 +763,7 @@ func TestTooMuchDataRequested(t *testing.T) { mm := &mockClientWithLimit{ limit: 3, - MockClient: *m, + MockClient: m, } config := DefaultConfig() From a12608395914f3e175f0f4ee849e126ef773738f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Negovanovi=C4=87?= Date: Tue, 8 Aug 2023 10:23:20 +0200 Subject: [PATCH 3/6] Add lint target to makefile --- Makefile | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Makefile b/Makefile index 4b7790c8..35359d00 100644 --- a/Makefile +++ b/Makefile @@ -3,3 +3,7 @@ build-artifacts: @echo "--> Build Artifacts" @sh -c ./scripts/build-artifacts.sh + +.PHONY: lint +lint: + golangci-lint run \ No newline at end of file From ead50330d738741ba577999a21c7cd96df083bf6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Negovanovi=C4=87?= Date: Tue, 8 Aug 2023 10:23:36 +0200 Subject: [PATCH 4/6] Misc fixes --- abi/encoding_test.go | 6 ++-- abi/testing.go | 5 ++- compiler/solidity.go | 2 +- compiler/solidity_test.go | 2 +- contract/contract_test.go | 15 +++++--- e2e/transaction_test.go | 3 +- jsonrpc/util.go | 1 + keystore/v4.go | 2 +- signing/eip712.go | 2 ++ signing/eip712_test.go | 2 +- structs.go | 4 +-- structs_unmarshal.go | 8 +++-- testutil/mock.go | 4 +-- testutil/server.go | 6 ++-- tracker/store/boltdb/bolt_store.go | 38 ++++++++++++++------ tracker/store/postgresql/postgresql_store.go | 4 ++- tracker/tracker_test.go | 25 ++++++------- 17 files changed, 82 insertions(+), 47 deletions(-) diff --git a/abi/encoding_test.go b/abi/encoding_test.go index 06726106..d41bf47c 100644 --- a/abi/encoding_test.go +++ b/abi/encoding_test.go @@ -583,7 +583,7 @@ func testEncodeDecode(t *testing.T, server *testutil.TestServer, tt *Type, input return nil } -func generateRandomArgs(n int) *Type { +func generateRandomArgs(r *rand.Rand, n int) *Type { inputs := []*TupleElem{} for i := 0; i < randomInt(1, 10); i++ { ttt, err := NewType(randomType()) @@ -602,7 +602,7 @@ func generateRandomArgs(n int) *Type { } func TestRandomEncoding(t *testing.T) { - rand.Seed(time.Now().UTC().UnixNano()) + r := rand.New(rand.NewSource(time.Now().UnixNano())) nStr := os.Getenv("RANDOM_TESTS") n, err := strconv.Atoi(nStr) @@ -616,7 +616,7 @@ func TestRandomEncoding(t *testing.T) { t.Run("", func(t *testing.T) { t.Parallel() - tt := generateRandomArgs(randomInt(1, 4)) + tt := generateRandomArgs(r, randomInt(1, 4)) input := generateRandomType(tt) if err := testEncodeDecode(t, server, tt, input); err != nil { diff --git a/abi/testing.go b/abi/testing.go index 89b79cc9..8a73e161 100644 --- a/abi/testing.go +++ b/abi/testing.go @@ -6,12 +6,15 @@ import ( "math/rand" "reflect" "strings" + "time" "github.com/umbracle/ethgo" ) +var randomGen = rand.New(rand.NewSource(time.Now().UnixNano())) + func randomInt(min, max int) int { - return min + rand.Intn(max-min) + return min + randomGen.Intn(max-min) } var randomTypes = []string{ diff --git a/compiler/solidity.go b/compiler/solidity.go index 8fe6b50f..9f328d62 100644 --- a/compiler/solidity.go +++ b/compiler/solidity.go @@ -83,7 +83,7 @@ func (s *Solidity) compileImpl(code string, files ...string) (*Output, error) { cmd.Stderr = &stderr if err := cmd.Run(); err != nil { - return nil, fmt.Errorf("failed to compile: %s", string(stderr.Bytes())) + return nil, fmt.Errorf("failed to compile: %s", stderr.String()) } var output *Output diff --git a/compiler/solidity_test.go b/compiler/solidity_test.go index 715287c4..437d33d2 100644 --- a/compiler/solidity_test.go +++ b/compiler/solidity_test.go @@ -119,7 +119,7 @@ func existsSolidity(t *testing.T, path string) bool { cmd.Stderr = &stderr cmd.Stdout = &stdout if err := cmd.Run(); err != nil { - t.Fatalf("solidity version failed: %s", string(stderr.Bytes())) + t.Fatalf("solidity version failed: %s", stderr.String()) } if len(stdout.Bytes()) == 0 { t.Fatal("empty output") diff --git a/contract/contract_test.go b/contract/contract_test.go index 7774a046..731d4e9e 100644 --- a/contract/contract_test.go +++ b/contract/contract_test.go @@ -99,7 +99,8 @@ func TestContract_Deploy(t *testing.T) { // create an address and fund it key, _ := wallet.GenerateKey() - s.Fund(key.Address()) + _, err := s.Fund(key.Address()) + require.NoError(t, err) p, _ := jsonrpc.NewClient(s.HTTPAddr()) @@ -137,7 +138,8 @@ func TestContract_Transaction(t *testing.T) { // create an address and fund it key, _ := wallet.GenerateKey() - s.Fund(key.Address()) + _, err := s.Fund(key.Address()) + require.NoError(t, err) cc := &testutil.Contract{} cc.AddEvent(testutil.NewEvent("A").Add("uint256", true)) @@ -170,7 +172,8 @@ func TestContract_CallAtBlock(t *testing.T) { // create an address and fund it key, _ := wallet.GenerateKey() - s.Fund(key.Address()) + _, err := s.Fund(key.Address()) + require.NoError(t, err) cc := &testutil.Contract{} cc.AddCallback(func() string { @@ -228,7 +231,8 @@ func TestContract_SendValueContractCall(t *testing.T) { s := testutil.NewTestServer(t) key, _ := wallet.GenerateKey() - s.Fund(key.Address()) + _, err := s.Fund(key.Address()) + assert.NoError(t, err) cc := &testutil.Contract{} cc.AddCallback(func() string { @@ -267,7 +271,8 @@ func TestContract_EIP1559(t *testing.T) { s := testutil.NewTestServer(t) key, _ := wallet.GenerateKey() - s.Fund(key.Address()) + _, err := s.Fund(key.Address()) + assert.NoError(t, err) cc := &testutil.Contract{} cc.AddOutputCaller("example") diff --git a/e2e/transaction_test.go b/e2e/transaction_test.go index a427fc72..3b2f62b3 100644 --- a/e2e/transaction_test.go +++ b/e2e/transaction_test.go @@ -19,7 +19,8 @@ func TestSendSignedTransaction(t *testing.T) { // add value to the new key value := big.NewInt(1000000000000000000) - s.Transfer(key.Address(), value) + _, err = s.Transfer(key.Address(), value) + assert.NoError(t, err) c, _ := jsonrpc.NewClient(s.HTTPAddr()) diff --git a/jsonrpc/util.go b/jsonrpc/util.go index 59aadfd2..23615c8c 100644 --- a/jsonrpc/util.go +++ b/jsonrpc/util.go @@ -26,6 +26,7 @@ func (a *ArgBig) Big() *big.Int { return &b } +//nolint:unused func encodeUintToHex(i uint64) string { return fmt.Sprintf("0x%x", i) } diff --git a/keystore/v4.go b/keystore/v4.go index 79b9fac0..6a4ecc4a 100644 --- a/keystore/v4.go +++ b/keystore/v4.go @@ -158,7 +158,7 @@ func normalizePassword(password string) string { if i == 0x7F { return true } - if 0x00 <= i && i <= 0x1F { + if i <= 0x1F { return true } if 0x80 <= i && i <= 0x9F { diff --git a/signing/eip712.go b/signing/eip712.go index 4ade5cb2..df9d0a9b 100644 --- a/signing/eip712.go +++ b/signing/eip712.go @@ -64,10 +64,12 @@ func decodeStructType(typ reflect.Type, result *map[string][]*EIP712Type) string return name } +//nolint:unused func isByteSlice(t reflect.Type) bool { return t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 } +//nolint:unused func isByteArray(t reflect.Type) bool { return t.Kind() == reflect.Array && t.Elem().Kind() == reflect.Uint8 } diff --git a/signing/eip712_test.go b/signing/eip712_test.go index 9ffd282b..36b713e8 100644 --- a/signing/eip712_test.go +++ b/signing/eip712_test.go @@ -38,7 +38,7 @@ func TestBuildMessage_Encode(t *testing.T) { } typedMsg := b.Build(msg) - _, ok := typedMsg.Message["msg1"].(interface{}) + _, ok := typedMsg.Message["msg1"].(map[string]interface{}) require.True(t, ok) _, ok = typedMsg.Message["msg2"].([]interface{}) diff --git a/structs.go b/structs.go index f8a24c13..e6011933 100644 --- a/structs.go +++ b/structs.go @@ -22,7 +22,7 @@ type Address [20]byte // HexToAddress converts an hex string value to an address object func HexToAddress(str string) Address { a := Address{} - a.UnmarshalText(completeHex(str, 20)) + _ = a.UnmarshalText(completeHex(str, 20)) return a } @@ -91,7 +91,7 @@ type Hash [32]byte // HexToHash converts an hex string value to a hash object func HexToHash(str string) Hash { h := Hash{} - h.UnmarshalText(completeHex(str, 32)) + _ = h.UnmarshalText(completeHex(str, 32)) return h } diff --git a/structs_unmarshal.go b/structs_unmarshal.go index 4b7ef4eb..06289424 100644 --- a/structs_unmarshal.go +++ b/structs_unmarshal.go @@ -646,7 +646,9 @@ func decodeHash(h *Hash, v *fastjson.Value, key string) error { h = &Hash{} } - h.UnmarshalText(b) + if err := h.UnmarshalText(b); err != nil { + return err + } return nil } @@ -655,7 +657,9 @@ func decodeAddr(a *Address, v *fastjson.Value, key string) error { if len(b) == 0 { return fmt.Errorf("field '%s' not found", key) } - a.UnmarshalText(b) + if err := a.UnmarshalText(b); err != nil { + return err + } return nil } diff --git a/testutil/mock.go b/testutil/mock.go index 1161d6f4..94172f51 100644 --- a/testutil/mock.go +++ b/testutil/mock.go @@ -91,9 +91,7 @@ func (d *MockClient) AddScenario(m MockList) { // add logs // remove any other logs for this block in case there are any - if _, ok := d.logs[block.Hash]; ok { - delete(d.logs, block.Hash) - } + delete(d.logs, block.Hash) d.AddLogs(b.GetLogs()) } diff --git a/testutil/server.go b/testutil/server.go index 2de865e3..013da9f5 100644 --- a/testutil/server.go +++ b/testutil/server.go @@ -31,10 +31,10 @@ var ( ) func getOpenPort() string { - rand.Seed(time.Now().UnixNano()) + r := rand.New(rand.NewSource(time.Now().UnixNano())) min, max := 12000, 15000 for { - port := strconv.Itoa(rand.Intn(max-min) + min) + port := strconv.Itoa(r.Intn(max-min) + min) server, err := net.Listen("tcp", ":"+port) if err == nil { server.Close() @@ -181,7 +181,7 @@ func (t *TestServer) IPCPath() string { // WSAddr returns the websocket endpoint func (t *TestServer) WSAddr() string { - return fmt.Sprintf("ws://localhost:8546") + return "ws://localhost:8546" } // HTTPAddr returns the http endpoint diff --git a/tracker/store/boltdb/bolt_store.go b/tracker/store/boltdb/bolt_store.go index 1340bab2..faf99f74 100644 --- a/tracker/store/boltdb/bolt_store.go +++ b/tracker/store/boltdb/bolt_store.go @@ -42,7 +42,9 @@ func (b *BoltStore) setupDB() error { if err != nil { return err } - defer txn.Rollback() + defer func() { + _ = txn.Rollback() + }() if _, err := txn.CreateBucketIfNotExists(dbConf); err != nil { return err @@ -61,7 +63,9 @@ func (b *BoltStore) Get(k string) (string, error) { if err != nil { return "", err } - defer txn.Rollback() + defer func() { + _ = txn.Rollback() + }() bucket := txn.Bucket(dbConf) val := bucket.Get([]byte(k)) @@ -75,7 +79,9 @@ func (b *BoltStore) ListPrefix(prefix string) ([]string, error) { if err != nil { return nil, err } - defer txn.Rollback() + defer func() { + err = txn.Rollback() + }() res := []string{} c := txn.Bucket(dbConf).Cursor() @@ -91,7 +97,9 @@ func (b *BoltStore) Set(k, v string) error { if err != nil { return err } - defer txn.Rollback() + defer func() { + _ = txn.Rollback() + }() bucket := txn.Bucket(dbConf) if err := bucket.Put([]byte(k), []byte(v)); err != nil { @@ -106,7 +114,9 @@ func (b *BoltStore) GetEntry(hash string) (store.Entry, error) { if err != nil { return nil, err } - defer txn.Rollback() + defer func() { + _ = txn.Rollback() + }() bucketName := append(dbLogs, []byte(hash)...) if _, err := txn.CreateBucketIfNotExists(bucketName); err != nil { @@ -134,7 +144,9 @@ func (e *Entry) LastIndex() (uint64, error) { if err != nil { return 0, err } - defer tx.Rollback() + defer func() { + _ = tx.Rollback() + }() curs := tx.Bucket(e.bucket).Cursor() if last, _ := curs.Last(); last != nil { @@ -154,7 +166,9 @@ func (e *Entry) StoreLogs(logs []*ethgo.Log) error { if err != nil { return err } - defer tx.Rollback() + defer func() { + _ = tx.Rollback() + }() indx, err := e.LastIndex() if err != nil { @@ -173,6 +187,7 @@ func (e *Entry) StoreLogs(logs []*ethgo.Log) error { return err } } + return tx.Commit() } @@ -184,7 +199,9 @@ func (e *Entry) RemoveLogs(indx uint64) error { if err != nil { return err } - defer tx.Rollback() + defer func() { + _ = tx.Rollback() + }() curs := tx.Bucket(e.bucket).Cursor() for k, _ := curs.Seek(indxKey); k != nil; k, _ = curs.Next() { @@ -192,7 +209,6 @@ func (e *Entry) RemoveLogs(indx uint64) error { return err } } - return tx.Commit() } @@ -202,7 +218,9 @@ func (e *Entry) GetLog(indx uint64, log *ethgo.Log) error { if err != nil { return err } - defer txn.Rollback() + defer func() { + _ = txn.Rollback() + }() bucket := txn.Bucket(e.bucket) val := bucket.Get(uint64ToBytes(indx)) diff --git a/tracker/store/postgresql/postgresql_store.go b/tracker/store/postgresql/postgresql_store.go index 71f1842c..65793f61 100644 --- a/tracker/store/postgresql/postgresql_store.go +++ b/tracker/store/postgresql/postgresql_store.go @@ -117,7 +117,9 @@ func (e *Entry) StoreLogs(logs []*ethgo.Log) error { if err != nil { return err } - defer tx.Rollback() + defer func() { + _ = tx.Rollback() + }() query := "INSERT INTO " + e.table + " (indx, tx_index, tx_hash, block_num, block_hash, address, data, topics) VALUES (:indx, :tx_index, :tx_hash, :block_num, :block_hash, :address, :data, :topics)" diff --git a/tracker/tracker_test.go b/tracker/tracker_test.go index 5a4b20a0..e1a6d0fc 100644 --- a/tracker/tracker_test.go +++ b/tracker/tracker_test.go @@ -21,6 +21,8 @@ import ( "github.com/umbracle/ethgo/tracker/store/inmem" ) +var randomGen = rand.New(rand.NewSource(time.Now().UnixNano())) + func testConfig() ConfigOption { return func(c *Config) { c.BatchSize = 10 @@ -157,7 +159,7 @@ func TestPreflight(t *testing.T) { l0 := testutil.MockList{} l0.Create(0, 100, func(b *testutil.MockBlock) { - b = b.Extra("1") + b.Extra("1") }) m.AddScenario(l0) @@ -187,7 +189,7 @@ func TestTrackerSyncerRestarts(t *testing.T) { if len(void) == 0 { l.Create(first, last, func(b *testutil.MockBlock) { if b.GetNum()%5 == 0 { - b = b.Log("0x1") + b.Log("0x1") } }) m.AddScenario(l) @@ -238,7 +240,7 @@ func testSyncerReconcile(t *testing.T, iniLen, forkNum, endLen int) { // test that the syncer can reconcile if there is a fork in the saved state l := testutil.MockList{} l.Create(0, iniLen, func(b *testutil.MockBlock) { - b = b.Log("0x01") + b.Log("0x01") }) m := &testutil.MockClient{} @@ -266,14 +268,14 @@ func testSyncerReconcile(t *testing.T, iniLen, forkNum, endLen int) { l1 := testutil.MockList{} l1.Create(0, endLen, func(b *testutil.MockBlock) { if b.GetNum() < forkNum { - b = b.Log("0x01") // old fork + b.Log("0x01") // old fork } else { if b.GetNum() == forkNum { - b = b.Log("0x02") + b.Log("0x02") } else { - b = b.Log("0x03") + b.Log("0x03") } - b = b.Extra("123") // used to set the new fork + b.Extra("123") // used to set the new fork } }) @@ -330,7 +332,7 @@ func TestTrackerSyncerReconcile(t *testing.T) { } func randomInt(min, max int) int { - return min + rand.Intn(max-min) + return min + randomGen.Intn(max-min) } func testTrackerSyncerRandom(t *testing.T, n int, backlog uint64) { @@ -369,10 +371,11 @@ func testTrackerSyncerRandom(t *testing.T, n int, backlog uint64) { count := 0 for j := c; j < c+num; j++ { - bb := testutil.Mock(j).Extra(forkID) + bb := testutil.Mock(j) + bb.Extra(forkID) if j != 0 { count++ - bb = bb.Log(forkID) + bb.Log(forkID) } l = append(l, bb) } @@ -435,8 +438,6 @@ func testTrackerSyncerRandom(t *testing.T, n int, backlog uint64) { } func TestTrackerSyncerRandom(t *testing.T) { - rand.Seed(time.Now().UTC().UnixNano()) - for i := 0; i < 100; i++ { t.Run("", func(t *testing.T) { testTrackerSyncerRandom(t, 100, uint64(randomInt(2, 10))) From 3a11644efba4c83885b7c3fc0808e8f687efc969 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Negovanovi=C4=87?= Date: Tue, 8 Aug 2023 14:13:42 +0200 Subject: [PATCH 5/6] Alternatives for deprecated functions --- 4byte/4byte.go | 4 ++-- Makefile | 2 +- abi/encoding_test.go | 8 ++------ cmd/abigen/gen.go | 6 +++--- compiler/solidity.go | 3 +-- compiler/solidity_test.go | 5 ++--- testutil/server.go | 3 +-- tracker/store/boltdb/bolt_store_test.go | 3 +-- tracker/tracker.go | 4 ++-- 9 files changed, 15 insertions(+), 23 deletions(-) diff --git a/4byte/4byte.go b/4byte/4byte.go index 4f6d4865..f211354c 100644 --- a/4byte/4byte.go +++ b/4byte/4byte.go @@ -3,7 +3,7 @@ package fourbyte import ( "encoding/hex" "encoding/json" - "io/ioutil" + "io" "net/http" ) @@ -28,7 +28,7 @@ func get(path string) (string, error) { } defer req.Body.Close() - data, err := ioutil.ReadAll(req.Body) + data, err := io.ReadAll(req.Body) if err != nil { return "", err } diff --git a/Makefile b/Makefile index 35359d00..56ef4487 100644 --- a/Makefile +++ b/Makefile @@ -6,4 +6,4 @@ build-artifacts: .PHONY: lint lint: - golangci-lint run \ No newline at end of file + golangci-lint run diff --git a/abi/encoding_test.go b/abi/encoding_test.go index d41bf47c..a2378930 100644 --- a/abi/encoding_test.go +++ b/abi/encoding_test.go @@ -4,12 +4,10 @@ import ( "encoding/hex" "fmt" "math/big" - "math/rand" "os" "reflect" "strconv" "testing" - "time" "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/compiler" @@ -583,7 +581,7 @@ func testEncodeDecode(t *testing.T, server *testutil.TestServer, tt *Type, input return nil } -func generateRandomArgs(r *rand.Rand, n int) *Type { +func generateRandomArgs(n int) *Type { inputs := []*TupleElem{} for i := 0; i < randomInt(1, 10); i++ { ttt, err := NewType(randomType()) @@ -602,8 +600,6 @@ func generateRandomArgs(r *rand.Rand, n int) *Type { } func TestRandomEncoding(t *testing.T) { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - nStr := os.Getenv("RANDOM_TESTS") n, err := strconv.Atoi(nStr) if err != nil { @@ -616,7 +612,7 @@ func TestRandomEncoding(t *testing.T) { t.Run("", func(t *testing.T) { t.Parallel() - tt := generateRandomArgs(r, randomInt(1, 4)) + tt := generateRandomArgs(randomInt(1, 4)) input := generateRandomType(tt) if err := testEncodeDecode(t, server, tt, input); err != nil { diff --git a/cmd/abigen/gen.go b/cmd/abigen/gen.go index ba63823d..9f5dc5ee 100644 --- a/cmd/abigen/gen.go +++ b/cmd/abigen/gen.go @@ -3,7 +3,7 @@ package abigen import ( "bytes" "fmt" - "io/ioutil" + "os" "path/filepath" "reflect" "strings" @@ -158,7 +158,7 @@ func gen(artifacts map[string]*compiler.Artifact, config *config, hash string) e if err := tmplAbi.Execute(&b, input); err != nil { return err } - if err := ioutil.WriteFile(filepath.Join(config.Output, filename+".go"), []byte(b.Bytes()), 0644); err != nil { + if err := os.WriteFile(filepath.Join(config.Output, filename+".go"), []byte(b.Bytes()), 0644); err != nil { return err } @@ -166,7 +166,7 @@ func gen(artifacts map[string]*compiler.Artifact, config *config, hash string) e if err := tmplBin.Execute(&b, input); err != nil { return err } - if err := ioutil.WriteFile(filepath.Join(config.Output, filename+"_artifacts.go"), []byte(b.Bytes()), 0644); err != nil { + if err := os.WriteFile(filepath.Join(config.Output, filename+"_artifacts.go"), []byte(b.Bytes()), 0644); err != nil { return err } } diff --git a/compiler/solidity.go b/compiler/solidity.go index 9f328d62..fd14d989 100644 --- a/compiler/solidity.go +++ b/compiler/solidity.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "os" "os/exec" @@ -127,7 +126,7 @@ func DownloadSolidity(version string, dst string, renameDst bool) error { } // tmp folder to download the binary - tmpDir, err := ioutil.TempDir("/tmp", "solc-") + tmpDir, err := os.MkdirTemp("/tmp", "solc-") if err != nil { return err } diff --git a/compiler/solidity_test.go b/compiler/solidity_test.go index 437d33d2..f70b0920 100644 --- a/compiler/solidity_test.go +++ b/compiler/solidity_test.go @@ -2,7 +2,6 @@ package compiler import ( "bytes" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -128,7 +127,7 @@ func existsSolidity(t *testing.T, path string) bool { } func TestDownloadSolidityCompiler(t *testing.T) { - dst1, err := ioutil.TempDir("/tmp", "ethgo-") + dst1, err := os.MkdirTemp("/tmp", "ethgo-") if err != nil { t.Fatal(err) } @@ -144,7 +143,7 @@ func TestDownloadSolidityCompiler(t *testing.T) { t.Fatal("it should exist") } - dst2, err := ioutil.TempDir("/tmp", "ethgo-") + dst2, err := os.MkdirTemp("/tmp", "ethgo-") if err != nil { t.Fatal(err) } diff --git a/testutil/server.go b/testutil/server.go index 013da9f5..e852b989 100644 --- a/testutil/server.go +++ b/testutil/server.go @@ -5,7 +5,6 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io/ioutil" "math/big" "math/rand" "net" @@ -76,7 +75,7 @@ type TestServer struct { // DeployTestServer creates a new Geth test server func DeployTestServer(t *testing.T, cb ServerConfigCallback) *TestServer { - tmpDir, err := ioutil.TempDir("/tmp", "geth-") + tmpDir, err := os.MkdirTemp("/tmp", "geth-") if err != nil { t.Fatalf("err: %s", err) } diff --git a/tracker/store/boltdb/bolt_store_test.go b/tracker/store/boltdb/bolt_store_test.go index 42b85758..a531a8c1 100644 --- a/tracker/store/boltdb/bolt_store_test.go +++ b/tracker/store/boltdb/bolt_store_test.go @@ -1,7 +1,6 @@ package trackerboltdb import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -10,7 +9,7 @@ import ( ) func setupDB(t *testing.T) (store.Store, func()) { - dir, err := ioutil.TempDir("/tmp", "boltdb-test") + dir, err := os.MkdirTemp("/tmp", "boltdb-test") if err != nil { t.Fatal(err) } diff --git a/tracker/tracker.go b/tracker/tracker.go index 08bdba6b..a765b354 100644 --- a/tracker/tracker.go +++ b/tracker/tracker.go @@ -6,7 +6,7 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io/ioutil" + "io" "log" "math/big" "strconv" @@ -168,7 +168,7 @@ func NewTracker(provider Provider, opts ...ConfigOption) (*Tracker, error) { provider: provider, config: config, BlockCh: make(chan *blocktracker.BlockEvent, 1), - logger: log.New(ioutil.Discard, "", log.LstdFlags), + logger: log.New(io.Discard, "", log.LstdFlags), ReadyCh: make(chan struct{}), store: config.Store, blockTracker: config.BlockTracker, From 6e5cea40a7b868cac6fec5050a44f9843e5bc001 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Negovanovi=C4=87?= Date: Tue, 8 Aug 2023 14:20:33 +0200 Subject: [PATCH 6/6] Fix TestRandomEncoding --- abi/encoding_test.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/abi/encoding_test.go b/abi/encoding_test.go index a2378930..72da19b1 100644 --- a/abi/encoding_test.go +++ b/abi/encoding_test.go @@ -641,9 +641,7 @@ func testDecodePanic(tt *Type, input interface{}) error { copy(buf, res1) buf[i] = 0xff - if _, err = Decode(tt, buf); err != nil { - return err - } + _, _ = Decode(tt, buf) } return nil