From cfc067dd24c79dd472fe4a3f97109d321b348d26 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 18:13:14 +0300 Subject: [PATCH 01/34] *: remove dead code Found by deadcode via golangci-lint. --- pkg/compiler/analysis.go | 4 --- pkg/consensus/recovery_message_test.go | 14 -------- pkg/core/helper_test.go | 47 -------------------------- pkg/core/interop_system_test.go | 22 ------------ pkg/core/native/ledger.go | 9 +---- pkg/core/native/util.go | 30 ---------------- pkg/core/util.go | 11 ------ pkg/encoding/fixedn/fixed8.go | 3 -- pkg/io/size.go | 12 ------- pkg/network/payload/extensible.go | 6 +--- pkg/network/server.go | 2 -- pkg/rpc/client/client.go | 1 - pkg/rpc/server/server_test.go | 6 ---- pkg/services/oracle/neofs/neofs.go | 5 --- pkg/util/bitfield/bitfield.go | 1 - pkg/wallet/account.go | 12 ------- 16 files changed, 2 insertions(+), 183 deletions(-) diff --git a/pkg/compiler/analysis.go b/pkg/compiler/analysis.go index b95139510..112c6945d 100644 --- a/pkg/compiler/analysis.go +++ b/pkg/compiler/analysis.go @@ -302,10 +302,6 @@ func isInteropPath(s string) bool { return strings.HasPrefix(s, interopPrefix) } -func isNativeHelpersPath(s string) bool { - return strings.HasPrefix(s, interopPrefix+"/native") -} - // canConvert returns true if type doesn't need to be converted on type assertion. func canConvert(s string) bool { if len(s) != 0 && s[0] == '*' { diff --git a/pkg/consensus/recovery_message_test.go b/pkg/consensus/recovery_message_test.go index 3af23db91..9fe19e263 100644 --- a/pkg/consensus/recovery_message_test.go +++ b/pkg/consensus/recovery_message_test.go @@ -7,7 +7,6 @@ import ( "github.com/nspcc-dev/dbft/payload" "github.com/nspcc-dev/neo-go/internal/testchain" "github.com/nspcc-dev/neo-go/pkg/config/netmode" - "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/stretchr/testify/require" ) @@ -157,16 +156,3 @@ func TestRecoveryMessage_Decode(t *testing.T) { require.Equal(t, gio.EOF, buf.Err) } */ - -func getKeys(t *testing.T, n int) []*privateKey { - privs := make([]*privateKey, 0, n) - for i := 0; i < n; i++ { - priv, err := keys.NewPrivateKey() - require.NoError(t, err) - require.NotNil(t, priv) - - privs = append(privs, &privateKey{PrivateKey: priv}) - } - - return privs -} diff --git a/pkg/core/helper_test.go b/pkg/core/helper_test.go index 41b0da005..32a470175 100644 --- a/pkg/core/helper_test.go +++ b/pkg/core/helper_test.go @@ -15,7 +15,6 @@ import ( "time" "github.com/nspcc-dev/neo-go/internal/testchain" - "github.com/nspcc-dev/neo-go/internal/testserdes" "github.com/nspcc-dev/neo-go/pkg/compiler" "github.com/nspcc-dev/neo-go/pkg/config" "github.com/nspcc-dev/neo-go/pkg/core/block" @@ -28,7 +27,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/core/state" "github.com/nspcc-dev/neo-go/pkg/core/storage" "github.com/nspcc-dev/neo-go/pkg/core/transaction" - "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/encoding/fixedn" "github.com/nspcc-dev/neo-go/pkg/io" @@ -180,51 +178,6 @@ func TestBug1728(t *testing.T) { require.Equal(t, aer.VMState, vm.HaltState) } -func getDecodedBlock(t *testing.T, i int) *block.Block { - data, err := getBlockData(i) - require.NoError(t, err) - - b, err := hex.DecodeString(data["raw"].(string)) - require.NoError(t, err) - - block := block.New(false) - require.NoError(t, testserdes.DecodeBinary(b, block)) - - return block -} - -func getBlockData(i int) (map[string]interface{}, error) { - b, err := ioutil.ReadFile(fmt.Sprintf("test_data/block_%d.json", i)) - if err != nil { - return nil, err - } - var data map[string]interface{} - if err := json.Unmarshal(b, &data); err != nil { - return nil, err - } - return data, err -} - -func newDumbBlock() *block.Block { - return &block.Block{ - Header: block.Header{ - Version: 0, - PrevHash: hash.Sha256([]byte("a")), - MerkleRoot: hash.Sha256([]byte("b")), - Timestamp: 100500, - Index: 1, - NextConsensus: hash.Hash160([]byte("a")), - Script: transaction.Witness{ - VerificationScript: []byte{0x51}, // PUSH1 - InvocationScript: []byte{0x61}, // NOP - }, - }, - Transactions: []*transaction.Transaction{ - transaction.New([]byte{byte(opcode.PUSH1)}, 0), - }, - } -} - // This function generates "../rpc/testdata/testblocks.acc" file which contains data // for RPC unit tests. It also is a nice integration test. // To generate new "../rpc/testdata/testblocks.acc", follow the steps: diff --git a/pkg/core/interop_system_test.go b/pkg/core/interop_system_test.go index 7c6f714ef..298bf29e9 100644 --- a/pkg/core/interop_system_test.go +++ b/pkg/core/interop_system_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/nspcc-dev/neo-go/internal/random" - "github.com/nspcc-dev/neo-go/pkg/core/block" "github.com/nspcc-dev/neo-go/pkg/core/dao" "github.com/nspcc-dev/neo-go/pkg/core/interop" "github.com/nspcc-dev/neo-go/pkg/core/interop/contract" @@ -451,27 +450,6 @@ func createVM(t *testing.T) (*vm.VM, *interop.Context, *Blockchain) { return v, context, chain } -func createVMAndPushBlock(t *testing.T) (*vm.VM, *block.Block, *interop.Context, *Blockchain) { - v, block, context, chain := createVMAndBlock(t) - v.Estack().PushVal(stackitem.NewInterop(block)) - return v, block, context, chain -} - -func createVMAndBlock(t *testing.T) (*vm.VM, *block.Block, *interop.Context, *Blockchain) { - block := newDumbBlock() - chain := newTestChain(t) - d := dao.NewSimple(storage.NewMemoryStore(), chain.GetConfig().StateRootInHeader) - context := chain.newInteropContext(trigger.Application, d, block, nil) - v := context.SpawnVM() - return v, block, context, chain -} - -func createVMAndPushTX(t *testing.T) (*vm.VM, *transaction.Transaction, *interop.Context, *Blockchain) { - v, tx, context, chain := createVMAndTX(t) - v.Estack().PushVal(stackitem.NewInterop(tx)) - return v, tx, context, chain -} - func createVMAndContractState(t *testing.T) (*vm.VM, *state.Contract, *interop.Context, *Blockchain) { script := []byte("testscript") m := manifest.NewManifest("Test") diff --git a/pkg/core/native/ledger.go b/pkg/core/native/ledger.go index 88e86f87e..4dfd6b313 100644 --- a/pkg/core/native/ledger.go +++ b/pkg/core/native/ledger.go @@ -25,14 +25,7 @@ type Ledger struct { interop.ContractMD } -const ( - ledgerContractID = -4 - - prefixBlockHash = 9 - prefixCurrentBlock = 12 - prefixBlock = 5 - prefixTransaction = 11 -) +const ledgerContractID = -4 // newLedger creates new Ledger native contract. func newLedger() *Ledger { diff --git a/pkg/core/native/util.go b/pkg/core/native/util.go index af7ffd6e7..73ac7f316 100644 --- a/pkg/core/native/util.go +++ b/pkg/core/native/util.go @@ -1,13 +1,11 @@ package native import ( - "encoding/binary" "encoding/hex" "fmt" "math/big" "github.com/nspcc-dev/neo-go/pkg/core/dao" - "github.com/nspcc-dev/neo-go/pkg/core/state" "github.com/nspcc-dev/neo-go/pkg/core/storage" "github.com/nspcc-dev/neo-go/pkg/encoding/bigint" "github.com/nspcc-dev/neo-go/pkg/io" @@ -36,34 +34,6 @@ func putSerializableToDAO(id int32, d dao.DAO, key []byte, item io.Serializable) return d.PutStorageItem(id, key, w.Bytes()) } -func getInt64WithKey(id int32, d dao.DAO, key []byte, defaultValue int64) int64 { - si := d.GetStorageItem(id, key) - if si == nil { - return defaultValue - } - return int64(binary.LittleEndian.Uint64(si)) -} - -func setInt64WithKey(id int32, dao dao.DAO, key []byte, value int64) error { - si := make(state.StorageItem, 8) - binary.LittleEndian.PutUint64(si, uint64(value)) - return dao.PutStorageItem(id, key, si) -} - -func getUint32WithKey(id int32, dao dao.DAO, key []byte, defaultValue uint32) uint32 { - si := dao.GetStorageItem(id, key) - if si == nil { - return defaultValue - } - return binary.LittleEndian.Uint32(si) -} - -func setUint32WithKey(id int32, dao dao.DAO, key []byte, value uint32) error { - si := make(state.StorageItem, 4) - binary.LittleEndian.PutUint32(si, value) - return dao.PutStorageItem(id, key, si) -} - func setIntWithKey(id int32, dao dao.DAO, key []byte, value int64) error { return dao.PutStorageItem(id, key, bigint.ToBytes(big.NewInt(value))) } diff --git a/pkg/core/util.go b/pkg/core/util.go index 2c1750ab8..325bac560 100644 --- a/pkg/core/util.go +++ b/pkg/core/util.go @@ -14,17 +14,6 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/opcode" ) -var ( - // governingTokenTX represents transaction that is used to create - // governing (NEO) token. It's a part of the genesis block. - governingTokenTX transaction.Transaction - - // utilityTokenTX represents transaction that is used to create - // utility (GAS) token. It's a part of the genesis block. It's mostly - // useful for its hash that represents GAS asset ID. - utilityTokenTX transaction.Transaction -) - // createGenesisBlock creates a genesis block based on the given configuration. func createGenesisBlock(cfg config.ProtocolConfiguration) (*block.Block, error) { validators, err := validatorsFromConfig(cfg) diff --git a/pkg/encoding/fixedn/fixed8.go b/pkg/encoding/fixedn/fixed8.go index ff92e6b6d..01abc8720 100644 --- a/pkg/encoding/fixedn/fixed8.go +++ b/pkg/encoding/fixedn/fixed8.go @@ -1,7 +1,6 @@ package fixedn import ( - "errors" "strconv" "strings" @@ -13,8 +12,6 @@ const ( decimals = 100000000 ) -var errInvalidString = errors.New("fixed8 must satisfy following regex \\d+(\\.\\d{1,8})?") - // Fixed8 represents a fixed-point number with precision 10^-8. type Fixed8 int64 diff --git a/pkg/io/size.go b/pkg/io/size.go index 93f7021f8..3075a77db 100644 --- a/pkg/io/size.go +++ b/pkg/io/size.go @@ -5,18 +5,6 @@ import ( "reflect" ) -var ( - bit8 byte - ui8 uint8 - ui16 uint16 - ui32 uint32 - ui64 uint64 - i8 int8 - i16 int16 - i32 int32 - i64 int64 -) - // This structure is used to calculate the wire size of the serializable // structure. It's an io.Writer that doesn't do any real writes, but instead // just counts the number of bytes to be written. diff --git a/pkg/network/payload/extensible.go b/pkg/network/payload/extensible.go index 529a8dc37..66891e7e7 100644 --- a/pkg/network/payload/extensible.go +++ b/pkg/network/payload/extensible.go @@ -2,7 +2,6 @@ package payload import ( "errors" - "math" "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/crypto/hash" @@ -10,10 +9,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -const ( - maxExtensibleCategorySize = 32 - maxExtensibleDataSize = math.MaxUint16 -) +const maxExtensibleCategorySize = 32 // Extensible represents payload containing arbitrary data. type Extensible struct { diff --git a/pkg/network/server.go b/pkg/network/server.go index e5f9f8e96..3e5d00808 100644 --- a/pkg/network/server.go +++ b/pkg/network/server.go @@ -41,12 +41,10 @@ const ( var ( errAlreadyConnected = errors.New("already connected") errIdenticalID = errors.New("identical node id") - errInvalidHandshake = errors.New("invalid handshake") errInvalidNetwork = errors.New("invalid network") errMaxPeers = errors.New("max peers reached") errServerShutdown = errors.New("server shutdown") errInvalidInvType = errors.New("invalid inventory type") - errInvalidHashStart = errors.New("invalid requested HashStart") ) type ( diff --git a/pkg/rpc/client/client.go b/pkg/rpc/client/client.go index bccd0d4a5..d112ef33c 100644 --- a/pkg/rpc/client/client.go +++ b/pkg/rpc/client/client.go @@ -21,7 +21,6 @@ import ( const ( defaultDialTimeout = 4 * time.Second defaultRequestTimeout = 4 * time.Second - defaultClientVersion = "2.0" // number of blocks after which cache is expired cacheTimeout = 100 ) diff --git a/pkg/rpc/server/server_test.go b/pkg/rpc/server/server_test.go index 526c54f2a..bd9df957b 100644 --- a/pkg/rpc/server/server_test.go +++ b/pkg/rpc/server/server_test.go @@ -46,11 +46,6 @@ type executor struct { httpSrv *httptest.Server } -const ( - defaultJSONRPC = "2.0" - defaultID = 1 -) - type rpcTestCase struct { name string params string @@ -66,7 +61,6 @@ const genesisBlockHash = "73fe50b5564d57118296cbab0a78fe7cb11c97b7699d07a9a21fab const verifyContractHash = "c50082e0d8364d61ce6933bd24027a3363474dce" const verifyContractAVM = "VwMAQS1RCDAhcAwU7p6iLCfjS9AUj8QQjgj3To9QSLLbMHFoE87bKGnbKJdA" const verifyWithArgsContractHash = "8744ffdd07af8e9f18ab90685c8c2ebfd37c6415" -const verifyWithArgsContractAVM = "VwIDeAwLZ29vZF9zdHJpbmeXJA15FSgJehHbIJciBRHbIHBoQA==" const invokescriptContractAVM = "VwcADBQBDAMOBQYMDQIODw0DDgcJAAAAANswcGhB+CfsjCGqJgQRQAwUDQ8DAgkAAgEDBwMEBQIBAA4GDAnbMHFpQfgn7IwhqiYEEkATQA==" var rpcTestCases = map[string][]rpcTestCase{ diff --git a/pkg/services/oracle/neofs/neofs.go b/pkg/services/oracle/neofs/neofs.go index ee09ae424..199310569 100644 --- a/pkg/services/oracle/neofs/neofs.go +++ b/pkg/services/oracle/neofs/neofs.go @@ -3,7 +3,6 @@ package neofs import ( "bytes" "context" - "crypto/sha256" "errors" "fmt" "net/url" @@ -24,10 +23,6 @@ const ( // URIScheme is the name of neofs URI scheme. URIScheme = "neofs" - // containerIDSize is the size of container id in bytes. - containerIDSize = sha256.Size - // objectIDSize is the size of container id in bytes. - objectIDSize = sha256.Size // rangeSep is a separator between offset and length. rangeSep = '|' diff --git a/pkg/util/bitfield/bitfield.go b/pkg/util/bitfield/bitfield.go index 8766c8d60..c2de953b4 100644 --- a/pkg/util/bitfield/bitfield.go +++ b/pkg/util/bitfield/bitfield.go @@ -10,7 +10,6 @@ type Field []uint64 // Bits and bytes count in a basic element of Field. const elemBits = 64 -const elemBytes = 8 // New creates a new bit field of specified length. Actual field length // can be rounded to the next multiple of 64, so it's a responsibility diff --git a/pkg/wallet/account.go b/pkg/wallet/account.go index 93f0c983f..f67a4fc17 100644 --- a/pkg/wallet/account.go +++ b/pkg/wallet/account.go @@ -61,18 +61,6 @@ type Contract struct { Deployed bool `json:"deployed"` } -// contract is an intermediate struct used for json unmarshalling. -type contract struct { - // Script is a hex-encoded script of the contract. - Script string `json:"script"` - - // A list of parameters used deploying this contract. - Parameters []ContractParam `json:"parameters"` - - // Indicates whether the contract has been deployed to the blockchain. - Deployed bool `json:"deployed"` -} - // ContractParam is a descriptor of a contract parameter // containing type and optional name. type ContractParam struct { From 73ecbbb7c6c0c2d9f5c482855824094dedb080ba Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 18:18:49 +0300 Subject: [PATCH 02/34] compiler: remove unused testPrintHash from test code --- pkg/compiler/native_test.go | 31 +++++++++++-------------------- 1 file changed, 11 insertions(+), 20 deletions(-) diff --git a/pkg/compiler/native_test.go b/pkg/compiler/native_test.go index 03c3fc77b..08012b03f 100644 --- a/pkg/compiler/native_test.go +++ b/pkg/compiler/native_test.go @@ -33,26 +33,17 @@ import ( func TestContractHashes(t *testing.T) { cs := native.NewContracts(true, map[string][]uint32{}) - require.Equal(t, []byte(neo.Hash), cs.NEO.Hash.BytesBE()) - require.Equal(t, []byte(gas.Hash), cs.GAS.Hash.BytesBE()) - require.Equal(t, []byte(oracle.Hash), cs.Oracle.Hash.BytesBE()) - require.Equal(t, []byte(roles.Hash), cs.Designate.Hash.BytesBE()) - require.Equal(t, []byte(policy.Hash), cs.Policy.Hash.BytesBE()) - require.Equal(t, []byte(nameservice.Hash), cs.NameService.Hash.BytesBE()) - require.Equal(t, []byte(ledger.Hash), cs.Ledger.Hash.BytesBE()) - require.Equal(t, []byte(management.Hash), cs.Management.Hash.BytesBE()) - require.Equal(t, []byte(notary.Hash), cs.Notary.Hash.BytesBE()) - require.Equal(t, []byte(crypto.Hash), cs.Crypto.Hash.BytesBE()) - require.Equal(t, []byte(std.Hash), cs.Std.Hash.BytesBE()) -} - -// testPrintHash is a helper for updating contract hashes. -func testPrintHash(u util.Uint160) { - fmt.Print(`"`) - for _, b := range u.BytesBE() { - fmt.Printf("\\x%02x", b) - } - fmt.Println(`"`) + require.Equalf(t, []byte(neo.Hash), cs.NEO.Hash.BytesBE(), "%q", string(cs.NEO.Hash.BytesBE())) + require.Equalf(t, []byte(gas.Hash), cs.GAS.Hash.BytesBE(), "%q", string(cs.GAS.Hash.BytesBE())) + require.Equalf(t, []byte(oracle.Hash), cs.Oracle.Hash.BytesBE(), "%q", string(cs.Oracle.Hash.BytesBE())) + require.Equalf(t, []byte(roles.Hash), cs.Designate.Hash.BytesBE(), "%q", string(cs.Designate.Hash.BytesBE())) + require.Equalf(t, []byte(policy.Hash), cs.Policy.Hash.BytesBE(), "%q", string(cs.Policy.Hash.BytesBE())) + require.Equalf(t, []byte(nameservice.Hash), cs.NameService.Hash.BytesBE(), "%q", string(cs.NameService.Hash.BytesBE())) + require.Equalf(t, []byte(ledger.Hash), cs.Ledger.Hash.BytesBE(), "%q", string(cs.Ledger.Hash.BytesBE())) + require.Equalf(t, []byte(management.Hash), cs.Management.Hash.BytesBE(), "%q", string(cs.Management.Hash.BytesBE())) + require.Equalf(t, []byte(notary.Hash), cs.Notary.Hash.BytesBE(), "%q", string(cs.Notary.Hash.BytesBE())) + require.Equalf(t, []byte(crypto.Hash), cs.Crypto.Hash.BytesBE(), "%q", string(cs.Crypto.Hash.BytesBE())) + require.Equalf(t, []byte(std.Hash), cs.Std.Hash.BytesBE(), "%q", string(cs.Std.Hash.BytesBE())) } func TestContractParameterTypes(t *testing.T) { From 8322607fd2e4ea50b1340742a7291b639b599e25 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 18:20:48 +0300 Subject: [PATCH 03/34] rpc/server: silence deadcode warning --- pkg/rpc/server/subscription_test.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pkg/rpc/server/subscription_test.go b/pkg/rpc/server/subscription_test.go index 58f4dc6d3..7f8872eed 100644 --- a/pkg/rpc/server/subscription_test.go +++ b/pkg/rpc/server/subscription_test.go @@ -16,6 +16,8 @@ import ( "go.uber.org/atomic" ) +const testOverflow = false + func wsReader(t *testing.T, ws *websocket.Conn, msgCh chan<- []byte, isFinished *atomic.Bool) { for { ws.SetReadDeadline(time.Now().Add(time.Second)) @@ -428,7 +430,10 @@ func TestWSClientsLimit(t *testing.T) { // that's going to happen because of network-level buffering, typical // number seen in tests is around ~3500 events, but it's not reliable enough, // thus this test is disabled. -func testSubscriptionOverflow(t *testing.T) { +func TestSubscriptionOverflow(t *testing.T) { + if !testOverflow { + return + } const blockCnt = notificationBufSize * 5 var receivedMiss bool From ad8ffee0ab8d1ffe492cf7a5d528845daf0cf915 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 18:24:16 +0300 Subject: [PATCH 04/34] *: remove redundant `return` statements Found by gosimple via golangci-lint. --- cli/nep17_test.go | 1 - pkg/compiler/binary_expr_test.go | 1 - 2 files changed, 2 deletions(-) diff --git a/cli/nep17_test.go b/cli/nep17_test.go index cc85497ee..5f94c344f 100644 --- a/cli/nep17_test.go +++ b/cli/nep17_test.go @@ -99,7 +99,6 @@ func TestNEP17Balance(t *testing.T) { t.Run("Bad wallet", func(t *testing.T) { e.RunWithError(t, append(cmdbalance, "--wallet", "/dev/null")...) }) - return } func TestNEP17Transfer(t *testing.T) { diff --git a/pkg/compiler/binary_expr_test.go b/pkg/compiler/binary_expr_test.go index 0afb2bcc2..899beaf89 100644 --- a/pkg/compiler/binary_expr_test.go +++ b/pkg/compiler/binary_expr_test.go @@ -339,7 +339,6 @@ func TestBooleanExprs(t *testing.T) { t.Run(triple[i].s, getBoolExprTestFunc(triple[i].val, triple[i].s)) } }) - return } func TestShortCircuit(t *testing.T) { From 07cdbb815c1c8007a6de3df1726021c8109ff8ad Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 18:29:39 +0300 Subject: [PATCH 05/34] *: drop unnecessary fmt.Sprintf uses gosimple: S1039: unnecessary use of fmt.Sprintf --- pkg/io/size.go | 2 +- pkg/vm/cli/cli_test.go | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pkg/io/size.go b/pkg/io/size.go index 3075a77db..9ee40eeba 100644 --- a/pkg/io/size.go +++ b/pkg/io/size.go @@ -59,7 +59,7 @@ func GetVarSize(value interface{}) int { case reflect.Ptr: vser, ok := v.Interface().(Serializable) if !ok { - panic(fmt.Sprintf("unable to calculate GetVarSize for a non-Serializable pointer")) + panic("unable to calculate GetVarSize for a non-Serializable pointer") } cw := counterWriter{} w := NewBinWriterFromIO(&cw) diff --git a/pkg/vm/cli/cli_test.go b/pkg/vm/cli/cli_test.go index 477e996ec..7eb4a2abd 100644 --- a/pkg/vm/cli/cli_test.go +++ b/pkg/vm/cli/cli_test.go @@ -324,7 +324,7 @@ func TestLoadAbort(t *testing.T) { "run", ) - e.checkNextLine(t, fmt.Sprintf("READY: loaded 2 instructions")) + e.checkNextLine(t, "READY: loaded 2 instructions") e.checkNextLine(t, "Error:.*at instruction 1.*ABORT") } @@ -349,7 +349,7 @@ func TestBreakpoint(t *testing.T) { e.checkNextLine(t, "no program loaded") e.checkNextLine(t, "no program loaded") e.checkNextLine(t, "no program loaded") - e.checkNextLine(t, fmt.Sprintf("READY: loaded 5 instructions")) + e.checkNextLine(t, "READY: loaded 5 instructions") e.checkError(t, ErrMissingParameter) e.checkError(t, ErrInvalidParameter) e.checkNextLine(t, "breakpoint added at instruction 2") @@ -415,19 +415,19 @@ func TestStepIntoOverOut(t *testing.T) { "loadhex "+script, "step", "stepinto", "stepout", "run") - e.checkNextLine(t, fmt.Sprintf("READY: loaded \\d+ instructions")) + e.checkNextLine(t, "READY: loaded 8 instructions") e.checkNextLine(t, "at breakpoint 1.*CALL") e.checkNextLine(t, "instruction pointer at.*NOP") e.checkStack(t, 5) - e.checkNextLine(t, fmt.Sprintf("READY: loaded \\d+ instructions")) + e.checkNextLine(t, "READY: loaded 8 instructions") e.checkNextLine(t, "at breakpoint.*CALL") e.checkNextLine(t, "instruction pointer at.*PUSH3") e.checkNextLine(t, "at breakpoint.*ADD") e.checkStack(t, 2, 3) e.checkStack(t, 5) - e.checkNextLine(t, fmt.Sprintf("READY: loaded \\d+ instructions")) + e.checkNextLine(t, "READY: loaded 8 instructions") e.checkNextLine(t, "at breakpoint 1.*CALL") e.checkNextLine(t, "instruction pointer at.*PUSH3") e.checkNextLine(t, "instruction pointer at.*NOP") From 017859485048df586d403ba7301346739b7f998c Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 18:32:11 +0300 Subject: [PATCH 06/34] *: simpilfy make() invocations gosimple: S1019: should use make([]byte, 64) instead --- pkg/core/blockchain_test.go | 4 ++-- pkg/network/payload/notary_request_test.go | 20 ++++++++++---------- pkg/network/server_test.go | 2 +- pkg/rpc/server/server_test.go | 4 ++-- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/pkg/core/blockchain_test.go b/pkg/core/blockchain_test.go index bec2d4a47..848c8e54d 100644 --- a/pkg/core/blockchain_test.go +++ b/pkg/core/blockchain_test.go @@ -1024,7 +1024,7 @@ func TestVerifyTx(t *testing.T) { nativeprices.NotaryVerificationPrice*bc.GetBaseExecFee() // Notary witness verification price tx.Scripts = []transaction.Witness{ { - InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), + InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: []byte{}, }, { @@ -1051,7 +1051,7 @@ func TestVerifyTx(t *testing.T) { tx.NetworkFee-- // to check that NetworkFee was set correctly in getPartiallyFilledTx tx.Scripts = []transaction.Witness{ { - InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), + InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: []byte{}, }, { diff --git a/pkg/network/payload/notary_request_test.go b/pkg/network/payload/notary_request_test.go index e148ab9ba..8e0bc6ea0 100644 --- a/pkg/network/payload/notary_request_test.go +++ b/pkg/network/payload/notary_request_test.go @@ -45,21 +45,21 @@ func TestNotaryRequestIsValid(t *testing.T) { MainTransaction: mainTx, FallbackTransaction: &transaction.Transaction{ Signers: []transaction.Signer{{Account: random.Uint160()}, {Account: random.Uint160()}}, - Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 65}, make([]byte, 64, 64)...)}, {}}, + Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 65}, make([]byte, 64)...)}, {}}, }, }, "fallback tx: invalid dummy Notary witness (non-empty verification script))": { MainTransaction: mainTx, FallbackTransaction: &transaction.Transaction{ Signers: []transaction.Signer{{Account: random.Uint160()}, {Account: random.Uint160()}}, - Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), VerificationScript: make([]byte, 1, 1)}, {}}, + Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: make([]byte, 1)}, {}}, }, }, "fallback tx: missing NotValidBefore attribute": { MainTransaction: mainTx, FallbackTransaction: &transaction.Transaction{ Signers: []transaction.Signer{{Account: random.Uint160()}, {Account: random.Uint160()}}, - Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), VerificationScript: make([]byte, 0)}, {}}, + Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: make([]byte, 0)}, {}}, }, }, "fallback tx: invalid number of Conflicts attributes": { @@ -67,7 +67,7 @@ func TestNotaryRequestIsValid(t *testing.T) { FallbackTransaction: &transaction.Transaction{ Attributes: []transaction.Attribute{{Type: transaction.NotValidBeforeT, Value: &transaction.NotValidBefore{Height: 123}}}, Signers: []transaction.Signer{{Account: random.Uint160()}, {Account: random.Uint160()}}, - Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), VerificationScript: make([]byte, 0)}, {}}, + Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: make([]byte, 0)}, {}}, }, }, "fallback tx: does not conflicts with main tx": { @@ -78,7 +78,7 @@ func TestNotaryRequestIsValid(t *testing.T) { {Type: transaction.ConflictsT, Value: &transaction.Conflicts{Hash: util.Uint256{}}}, }, Signers: []transaction.Signer{{Account: random.Uint160()}, {Account: random.Uint160()}}, - Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), VerificationScript: make([]byte, 0)}, {}}, + Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: make([]byte, 0)}, {}}, }, }, "fallback tx: missing NotaryAssisted attribute": { @@ -89,7 +89,7 @@ func TestNotaryRequestIsValid(t *testing.T) { {Type: transaction.ConflictsT, Value: &transaction.Conflicts{Hash: mainTx.Hash()}}, }, Signers: []transaction.Signer{{Account: random.Uint160()}, {Account: random.Uint160()}}, - Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), VerificationScript: make([]byte, 0)}, {}}, + Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: make([]byte, 0)}, {}}, }, }, "fallback tx: non-zero NKeys": { @@ -101,7 +101,7 @@ func TestNotaryRequestIsValid(t *testing.T) { {Type: transaction.NotaryAssistedT, Value: &transaction.NotaryAssisted{NKeys: 1}}, }, Signers: []transaction.Signer{{Account: random.Uint160()}, {Account: random.Uint160()}}, - Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), VerificationScript: make([]byte, 0)}, {}}, + Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: make([]byte, 0)}, {}}, }, }, "fallback tx: ValidUntilBlock mismatch": { @@ -114,7 +114,7 @@ func TestNotaryRequestIsValid(t *testing.T) { {Type: transaction.NotaryAssistedT, Value: &transaction.NotaryAssisted{NKeys: 0}}, }, Signers: []transaction.Signer{{Account: random.Uint160()}, {Account: random.Uint160()}}, - Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), VerificationScript: make([]byte, 0)}, {}}, + Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: make([]byte, 0)}, {}}, }, }, } @@ -134,7 +134,7 @@ func TestNotaryRequestIsValid(t *testing.T) { {Type: transaction.NotaryAssistedT, Value: &transaction.NotaryAssisted{NKeys: 0}}, }, Signers: []transaction.Signer{{Account: random.Uint160()}, {Account: random.Uint160()}}, - Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), VerificationScript: make([]byte, 0)}, {}}, + Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: make([]byte, 0)}, {}}, }, } require.NoError(t, p.isValid()) @@ -164,7 +164,7 @@ func TestNotaryRequestBytesFromBytes(t *testing.T) { }, Signers: []transaction.Signer{{Account: util.Uint160{1, 4, 7}}, {Account: util.Uint160{9, 8, 7}}}, Scripts: []transaction.Witness{ - {InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), VerificationScript: make([]byte, 0)}, + {InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: make([]byte, 0)}, {InvocationScript: []byte{1, 2, 3}, VerificationScript: []byte{1, 2, 3}}}, } _ = fallbackTx.Hash() diff --git a/pkg/network/server_test.go b/pkg/network/server_test.go index cf20c9a09..da1385430 100644 --- a/pkg/network/server_test.go +++ b/pkg/network/server_test.go @@ -535,7 +535,7 @@ func TestGetData(t *testing.T) { {Type: transaction.NotaryAssistedT, Value: &transaction.NotaryAssisted{NKeys: 0}}, }, Signers: []transaction.Signer{{Account: random.Uint160()}, {Account: random.Uint160()}}, - Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), VerificationScript: make([]byte, 0)}, {InvocationScript: []byte{}, VerificationScript: []byte{}}}, + Scripts: []transaction.Witness{{InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: make([]byte, 0)}, {InvocationScript: []byte{}, VerificationScript: []byte{}}}, } fallbackTx.Size() fallbackTx.Hash() diff --git a/pkg/rpc/server/server_test.go b/pkg/rpc/server/server_test.go index bd9df957b..fc06ebcc3 100644 --- a/pkg/rpc/server/server_test.go +++ b/pkg/rpc/server/server_test.go @@ -1088,7 +1088,7 @@ func TestSubmitNotaryRequest(t *testing.T) { }, Signers: []transaction.Signer{{Account: util.Uint160{1, 4, 7}}, {Account: util.Uint160{9, 8, 7}}}, Scripts: []transaction.Witness{ - {InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), VerificationScript: make([]byte, 0)}, + {InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: make([]byte, 0)}, {InvocationScript: []byte{1, 2, 3}, VerificationScript: []byte{1, 2, 3}}}, } p := &payload.P2PNotaryRequest{ @@ -1126,7 +1126,7 @@ func TestSubmitNotaryRequest(t *testing.T) { }, Signers: []transaction.Signer{{Account: chain.GetNotaryContractScriptHash()}, {Account: sender.GetScriptHash()}}, Scripts: []transaction.Witness{ - {InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64, 64)...), VerificationScript: []byte{}}, + {InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, make([]byte, 64)...), VerificationScript: []byte{}}, }, NetworkFee: 2_0000_0000, } From cf59bd878df0eabcfbfe1c091bd5556289d7fdf7 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 18:38:24 +0300 Subject: [PATCH 07/34] native: simplify escaping in regexp.MustCompile() gosimple: S1007: should use raw string (`...`) with regexp.MustCompile to avoid having to escape twice --- pkg/core/native/name_service.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/core/native/name_service.go b/pkg/core/native/name_service.go index d39d8e3c4..b2a950699 100644 --- a/pkg/core/native/name_service.go +++ b/pkg/core/native/name_service.go @@ -64,8 +64,8 @@ const ( var ( // Lookahead is not supported by Go, but it is simple `(?=.{3,255}$)`, // so we check name length explicitly. - nameRegex = regexp.MustCompile("^([a-z0-9]{1,62}\\.)+[a-z][a-z0-9]{0,15}$") - ipv4Regex = regexp.MustCompile("^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])$") + nameRegex = regexp.MustCompile(`^([a-z0-9]{1,62}\.)+[a-z][a-z0-9]{0,15}$`) + ipv4Regex = regexp.MustCompile(`^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])$`) ipv6Regex = regexp.MustCompile("(?:^)(([0-9a-f]{1,4}:){7,7}[0-9a-f]{1,4}|([0-9a-f]{1,4}:){1,7}:|([0-9a-f]{1,4}:){1,6}:[0-9a-f]{1,4}|([0-9a-f]{1,4}:){1,5}(:[0-9a-f]{1,4}){1,2}|([0-9a-f]{1,4}:){1,4}(:[0-9a-f]{1,4}){1,3}|([0-9a-f]{1,4}:){1,3}(:[0-9a-f]{1,4}){1,4}|([0-9a-f]{1,4}:){1,2}(:[0-9a-f]{1,4}){1,5}|[0-9a-f]{1,4}:((:[0-9a-f]{1,4}){1,6})|:((:[0-9a-f]{1,4}){1,7}|:))$") rootRegex = regexp.MustCompile("^[a-z][a-z0-9]{0,15}$") ) From bd48454c72ba350617770b76e6c919ab3155c277 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 18:40:41 +0300 Subject: [PATCH 08/34] mempool: simpilfy boolean comparisons in test code gosimple: S1008: should use 'return t == tx2' instead of 'if t == tx2 { return true }; return false' --- pkg/core/mempool/mem_pool_test.go | 10 ++-------- pkg/core/mempool/subscriptions_test.go | 5 +---- 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/pkg/core/mempool/mem_pool_test.go b/pkg/core/mempool/mem_pool_test.go index 694ce8960..a7e73839e 100644 --- a/pkg/core/mempool/mem_pool_test.go +++ b/pkg/core/mempool/mem_pool_test.go @@ -298,10 +298,7 @@ func TestMemPoolFees(t *testing.T) { // check whether sender's fee updates correctly mp.RemoveStale(func(t *transaction.Transaction) bool { - if t == tx2 { - return true - } - return false + return t == tx2 }, fs) require.Equal(t, 1, len(mp.fees)) require.Equal(t, utilityBalanceAndFees{ @@ -311,10 +308,7 @@ func TestMemPoolFees(t *testing.T) { // there should be nothing left mp.RemoveStale(func(t *transaction.Transaction) bool { - if t == tx3 { - return true - } - return false + return t == tx3 }, fs) require.Equal(t, 0, len(mp.fees)) } diff --git a/pkg/core/mempool/subscriptions_test.go b/pkg/core/mempool/subscriptions_test.go index 67557455f..a2fb3a91f 100644 --- a/pkg/core/mempool/subscriptions_test.go +++ b/pkg/core/mempool/subscriptions_test.go @@ -75,10 +75,7 @@ func TestSubscriptions(t *testing.T) { // remove stale mp.RemoveStale(func(tx *transaction.Transaction) bool { - if tx.Hash().Equals(txs[2].Hash()) { - return false - } - return true + return !tx.Hash().Equals(txs[2].Hash()) }, fs) require.Eventually(t, func() bool { return len(subChan1) == 1 && len(subChan2) == 1 }, time.Second, time.Millisecond*100) event1 = <-subChan1 From 7af67d2a3cbe9bed7a6b109bebe2a26ea069c25b Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 18:42:50 +0300 Subject: [PATCH 09/34] vm/cli: simplify buffer-related code gosimple: S1030: should use buf.String() instead of string(buf.Bytes()) --- pkg/vm/cli/cli.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/vm/cli/cli.go b/pkg/vm/cli/cli.go index 3e3495dd1..99988f280 100644 --- a/pkg/vm/cli/cli.go +++ b/pkg/vm/cli/cli.go @@ -589,7 +589,7 @@ func Parse(args []string) (string, error) { if err := w.Flush(); err != nil { return "", err } - return string(buf.Bytes()), nil + return buf.String(), nil } func parseArgs(args []string) ([]stackitem.Item, error) { From de5e61588d1206cfd65f2473dd7a35275112182b Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 18:44:35 +0300 Subject: [PATCH 10/34] vm: simplify some test code gosimple: S1017: should replace this `if` statement with an unconditional `strings.TrimPrefix` --- pkg/vm/json_test.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/pkg/vm/json_test.go b/pkg/vm/json_test.go index f5f85695c..fd3f87860 100644 --- a/pkg/vm/json_test.go +++ b/pkg/vm/json_test.go @@ -454,8 +454,6 @@ func decodeBytes(data []byte) ([]byte, error) { } func decodeHex(s string) ([]byte, error) { - if strings.HasPrefix(s, "0x") { - s = s[2:] - } + s = strings.TrimPrefix(s, "0x") return hex.DecodeString(s) } From 92dbb3c4b97431d8a1a3a00f308a2a71129d20d7 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 18:53:12 +0300 Subject: [PATCH 11/34] *: fix all `unused` warnings From golangci-lint. --- pkg/compiler/codegen.go | 27 --------------------------- pkg/core/mpt/batch_test.go | 2 ++ pkg/core/native/name_service.go | 11 ----------- pkg/core/native/nonfungible.go | 2 ++ pkg/services/oracle/transaction.go | 12 ------------ 5 files changed, 4 insertions(+), 50 deletions(-) diff --git a/pkg/compiler/codegen.go b/pkg/compiler/codegen.go index 6bb8b2c62..f80311da5 100644 --- a/pkg/compiler/codegen.go +++ b/pkg/compiler/codegen.go @@ -1521,33 +1521,6 @@ func getJumpForToken(tok token.Token, typ types.Type) (opcode.Opcode, bool) { return 0, false } -// getByteArray returns byte array value from constant expr. -// Only literals are supported. -func (c *codegen) getByteArray(expr ast.Expr) []byte { - switch t := expr.(type) { - case *ast.CompositeLit: - if !isByteSlice(c.typeOf(t.Type)) { - return nil - } - buf := make([]byte, len(t.Elts)) - for i := 0; i < len(t.Elts); i++ { - t := c.typeAndValueOf(t.Elts[i]) - val, _ := constant.Int64Val(t.Value) - buf[i] = byte(val) - } - return buf - case *ast.CallExpr: - if tv := c.typeAndValueOf(t.Args[0]); tv.Value != nil { - val := constant.StringVal(tv.Value) - return []byte(val) - } - - return nil - default: - return nil - } -} - func (c *codegen) convertSyscall(f *funcScope, expr *ast.CallExpr) { for _, arg := range expr.Args[1:] { ast.Walk(c, arg) diff --git a/pkg/core/mpt/batch_test.go b/pkg/core/mpt/batch_test.go index eebc21caa..dffb4b9ae 100644 --- a/pkg/core/mpt/batch_test.go +++ b/pkg/core/mpt/batch_test.go @@ -277,6 +277,8 @@ func TestTrie_PutBatch(t *testing.T) { testPut(t, ps, tr1, tr2) } +var _ = printNode + // This function is unused, but is helpful for debugging // as it provides more readable Trie representation compared to // `spew.Dump()` diff --git a/pkg/core/native/name_service.go b/pkg/core/native/name_service.go index b2a950699..0044624d3 100644 --- a/pkg/core/native/name_service.go +++ b/pkg/core/native/name_service.go @@ -711,17 +711,6 @@ func (sl stringList) index(s string) (int, bool) { return index, index < len(sl) && sl[index] == s } -func (sl *stringList) remove(s string) bool { - index, has := sl.index(s) - if !has { - return false - } - - copy((*sl)[index:], (*sl)[index+1:]) - *sl = (*sl)[:len(*sl)-1] - return true -} - func (sl *stringList) add(s string) bool { index, has := sl.index(s) if has { diff --git a/pkg/core/native/nonfungible.go b/pkg/core/native/nonfungible.go index 03cd67ef7..4288824f7 100644 --- a/pkg/core/native/nonfungible.go +++ b/pkg/core/native/nonfungible.go @@ -305,6 +305,8 @@ func (n *nonfungible) postTransfer(ic *interop.Context, from, to *util.Uint160, } } +var _ = (*nonfungible).burn // fix unused warning + func (n *nonfungible) burn(ic *interop.Context, tokenID []byte) { key := n.getTokenKey(tokenID) n.burnByKey(ic, key) diff --git a/pkg/services/oracle/transaction.go b/pkg/services/oracle/transaction.go index 6e38b8416..b76552f28 100644 --- a/pkg/services/oracle/transaction.go +++ b/pkg/services/oracle/transaction.go @@ -117,15 +117,3 @@ func finalizeTx(oracleNodes keys.PublicKeys, tx *transaction.Transaction, txSigs tx.Scripts[1].InvocationScript = w.Bytes() return true } - -func (t *incompleteTx) getRequest() *state.OracleRequest { - t.RLock() - defer t.RUnlock() - return t.request -} - -func (t *incompleteTx) getTime() time.Time { - t.RLock() - defer t.RUnlock() - return t.time -} From 333f778aa623e437098e1e5fb768be242a9a2582 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 19:10:31 +0300 Subject: [PATCH 12/34] *: drop empty branches Fix this warning from staticcheck: SA9003: empty branch --- pkg/core/fee/calculate.go | 4 ++-- pkg/rpc/client/client.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/core/fee/calculate.go b/pkg/core/fee/calculate.go index 7a64caa2a..c15874932 100644 --- a/pkg/core/fee/calculate.go +++ b/pkg/core/fee/calculate.go @@ -25,9 +25,9 @@ func Calculate(base int64, script []byte) (int64, int) { size += io.GetVarSize(sizeInv) + sizeInv + io.GetVarSize(script) netFee += calculateMultisig(base, m) + calculateMultisig(base, n) netFee += base * ECDSAVerifyPrice * int64(n) - } else { + } /*else { // We can support more contract types in the future. - } + }*/ return netFee, size } diff --git a/pkg/rpc/client/client.go b/pkg/rpc/client/client.go index d112ef33c..4623a9070 100644 --- a/pkg/rpc/client/client.go +++ b/pkg/rpc/client/client.go @@ -91,8 +91,8 @@ func New(ctx context.Context, endpoint string, opts Options) (*Client, error) { } // TODO(@antdm): Enable SSL. - if opts.Cert != "" && opts.Key != "" { - } + // if opts.Cert != "" && opts.Key != "" { + // } cl := &Client{ ctx: ctx, From b8ba923874736f3df8dee82f356300c64cf6a538 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 19:12:09 +0300 Subject: [PATCH 13/34] standard: improve testing code staticcheck: SA4021: x = append(y) is equivalent to x = y --- pkg/smartcontract/manifest/standard/comply_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/smartcontract/manifest/standard/comply_test.go b/pkg/smartcontract/manifest/standard/comply_test.go index 159815cc0..0d218c536 100644 --- a/pkg/smartcontract/manifest/standard/comply_test.go +++ b/pkg/smartcontract/manifest/standard/comply_test.go @@ -60,7 +60,7 @@ func TestComplyMethodParameterCount(t *testing.T) { t.Run("Event", func(t *testing.T) { m := fooMethodBarEvent() ev := m.ABI.GetEvent("bar") - ev.Parameters = append(ev.Parameters[:0]) + ev.Parameters = ev.Parameters[:0] err := Comply(m, &Standard{Manifest: *fooMethodBarEvent()}) require.True(t, errors.Is(err, ErrInvalidParameterCount)) }) From d15cacc1baba50f27c4ab2a0d7c394a1a8bafa1f Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 19:15:21 +0300 Subject: [PATCH 14/34] rpc/client: fix broken test code SA1024: cutset contains duplicate characters (staticcheck) --- pkg/rpc/client/wsclient_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/rpc/client/wsclient_test.go b/pkg/rpc/client/wsclient_test.go index 84ba6602a..61b1cd9c7 100644 --- a/pkg/rpc/client/wsclient_test.go +++ b/pkg/rpc/client/wsclient_test.go @@ -344,7 +344,7 @@ func TestNewWS(t *testing.T) { require.NoError(t, c.Init()) }) t.Run("bad URL", func(t *testing.T) { - _, err := NewWS(context.TODO(), strings.Trim(srv.URL, "http://"), Options{}) + _, err := NewWS(context.TODO(), strings.TrimPrefix(srv.URL, "http://"), Options{}) require.Error(t, err) }) } From b5ff87c2bdf5807a3e66703a9483ef16dd5644fb Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 19:27:02 +0300 Subject: [PATCH 15/34] native: fix minimum deployment fee setting SA4003: no value of type uint32 is less than 0 (staticcheck) But it's more involved than that, we should allow any positive big.Int here. --- pkg/core/native/management.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/core/native/management.go b/pkg/core/native/management.go index 6b73c2528..2a1bc77d5 100644 --- a/pkg/core/native/management.go +++ b/pkg/core/native/management.go @@ -409,14 +409,14 @@ func (m *Management) GetMinimumDeploymentFee(dao dao.DAO) int64 { } func (m *Management) setMinimumDeploymentFee(ic *interop.Context, args []stackitem.Item) stackitem.Item { - value := toUint32(args[0]) - if value < 0 { - panic(fmt.Errorf("MinimumDeploymentFee cannot be negative")) + value := toBigInt(args[0]) + if value.Sign() < 0 { + panic("MinimumDeploymentFee cannot be negative") } if !m.NEO.checkCommittee(ic) { panic("invalid committee signature") } - err := setIntWithKey(m.ID, ic.DAO, keyMinimumDeploymentFee, int64(value)) + err := ic.DAO.PutStorageItem(m.ID, keyMinimumDeploymentFee, bigint.ToBytes(value)) if err != nil { panic(err) } From 78bf1721084800cd17813272ac06606f3bd04761 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 19:29:45 +0300 Subject: [PATCH 16/34] network: drop some not really useful test code SA4010: this result of append is never used, except maybe in other appends (staticcheck) --- pkg/network/discovery_test.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/pkg/network/discovery_test.go b/pkg/network/discovery_test.go index 9c8fb1aad..83464a26f 100644 --- a/pkg/network/discovery_test.go +++ b/pkg/network/discovery_test.go @@ -197,12 +197,10 @@ func TestSeedDiscovery(t *testing.T) { d := NewDefaultDiscovery(seeds, time.Second/10, ts) d.RequestRemote(len(seeds)) - dialled := make([]string, 0) for i := 0; i < connRetries*2; i++ { for range seeds { select { - case a := <-ts.dialCh: - dialled = append(dialled, a) + case <-ts.dialCh: case <-time.After(time.Second): t.Fatalf("timeout expecting for transport dial") } From ec50bb4041bfa4f4400e4af778595884e4b72b23 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 19:33:27 +0300 Subject: [PATCH 17/34] cli/wallet: fix error handling ineffectual assignment to err (ineffassign) `err` is shadowed at `tx, err = c.CreateNEP11TransferTx()` line. --- cli/wallet/nep11.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cli/wallet/nep11.go b/cli/wallet/nep11.go index 322cbc6d0..fe92ce857 100644 --- a/cli/wallet/nep11.go +++ b/cli/wallet/nep11.go @@ -243,7 +243,9 @@ func signAndSendNEP11Transfer(ctx *cli.Context, c *client.Client, acc *wallet.Ac err error ) if amount != nil { - from, err := address.StringToUint160(acc.Address) + var from util.Uint160 + + from, err = address.StringToUint160(acc.Address) if err != nil { return cli.NewExitError(fmt.Errorf("bad account address: %w", err), 1) } From 4cd3da99b429f66845ac35312e4170bda8b5d1c1 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 19:37:14 +0300 Subject: [PATCH 18/34] core: fix ineffassign warning in test code ineffectual assignment to err (ineffassign) --- pkg/core/blockchain_test.go | 1 + pkg/core/native_designate_test.go | 4 ++-- pkg/core/stateroot_test.go | 2 ++ 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/pkg/core/blockchain_test.go b/pkg/core/blockchain_test.go index 848c8e54d..3bbf4b043 100644 --- a/pkg/core/blockchain_test.go +++ b/pkg/core/blockchain_test.go @@ -238,6 +238,7 @@ func TestGetBlock(t *testing.T) { t.Run("non-empty block", func(t *testing.T) { tx, err := testchain.NewTransferFromOwner(bc, bc.contracts.NEO.Hash, random.Uint160(), 1, 1, 1000) + require.NoError(t, err) b := bc.newBlock(tx) require.NoError(t, bc.AddHeaders(&b.Header)) diff --git a/pkg/core/native_designate_test.go b/pkg/core/native_designate_test.go index f66d464fc..6f8bacb7f 100644 --- a/pkg/core/native_designate_test.go +++ b/pkg/core/native_designate_test.go @@ -130,10 +130,10 @@ func TestDesignate_DesignateAsRole(t *testing.T) { ic.SpawnVM() ic.VM.LoadScript([]byte{byte(opcode.RET)}) - pubs, index, err := des.GetDesignatedByRole(bc.dao, 0xFF, 255) + _, _, err := des.GetDesignatedByRole(bc.dao, 0xFF, 255) require.True(t, errors.Is(err, native.ErrInvalidRole), "got: %v", err) - pubs, index, err = des.GetDesignatedByRole(bc.dao, noderoles.Oracle, 255) + pubs, index, err := des.GetDesignatedByRole(bc.dao, noderoles.Oracle, 255) require.NoError(t, err) require.Equal(t, 0, len(pubs)) require.Equal(t, uint32(0), index) diff --git a/pkg/core/stateroot_test.go b/pkg/core/stateroot_test.go index fafdc0c82..39df0e959 100644 --- a/pkg/core/stateroot_test.go +++ b/pkg/core/stateroot_test.go @@ -215,6 +215,7 @@ func TestStateRootFull(t *testing.T) { require.Eventually(t, func() bool { return lastHeight.Load() == 2 }, time.Second, time.Millisecond) checkVoteBroadcasted(t, bc, lastValidated.Load().(*payload.Extensible), 2, 1) _, err = persistBlock(bc) + require.NoError(t, err) require.Eventually(t, func() bool { return lastHeight.Load() == 3 }, time.Second, time.Millisecond) checkVoteBroadcasted(t, bc, lastValidated.Load().(*payload.Extensible), 3, 1) @@ -257,6 +258,7 @@ func checkVoteBroadcasted(t *testing.T, bc *Blockchain, p *payload.Extensible, require.Equal(t, int32(valIndex), vote.ValidatorIndex) pubs, _, err := bc.contracts.Designate.GetDesignatedByRole(bc.dao, noderoles.StateValidator, bc.BlockHeight()) + require.NoError(t, err) require.True(t, len(pubs) > int(valIndex)) require.True(t, pubs[valIndex].VerifyHashable(vote.Signature, uint32(netmode.UnitTestNet), r)) } From 601841ef35a395860a8f22534f78a162a6071571 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 19:41:23 +0300 Subject: [PATCH 19/34] *: drop unused structure fields Found by structcheck: `good` is unused (structcheck) and alike. --- pkg/compiler/vars.go | 1 - pkg/network/helper_test.go | 1 - pkg/network/tcp_peer.go | 2 -- pkg/rpc/server/server.go | 1 - 4 files changed, 5 deletions(-) diff --git a/pkg/compiler/vars.go b/pkg/compiler/vars.go index 4753d56f8..7b21151a4 100644 --- a/pkg/compiler/vars.go +++ b/pkg/compiler/vars.go @@ -6,7 +6,6 @@ import ( type varScope struct { localsCnt int - argCnt int arguments map[string]int locals []map[string]varInfo } diff --git a/pkg/network/helper_test.go b/pkg/network/helper_test.go index 0be730bb1..4a1779a78 100644 --- a/pkg/network/helper_test.go +++ b/pkg/network/helper_test.go @@ -19,7 +19,6 @@ import ( type testDiscovery struct { sync.Mutex bad []string - good []string connected []string unregistered []string backfill []string diff --git a/pkg/network/tcp_peer.go b/pkg/network/tcp_peer.go index d0ba1c576..85678d297 100644 --- a/pkg/network/tcp_peer.go +++ b/pkg/network/tcp_peer.go @@ -58,8 +58,6 @@ type TCPPeer struct { p2pSendQ chan []byte hpSendQ chan []byte - wg sync.WaitGroup - // track outstanding getaddr requests. getAddrSent atomic.Int32 diff --git a/pkg/rpc/server/server.go b/pkg/rpc/server/server.go index 4d65a437e..ab3e5bca7 100644 --- a/pkg/rpc/server/server.go +++ b/pkg/rpc/server/server.go @@ -59,7 +59,6 @@ type ( subsLock sync.RWMutex subscribers map[*subscriber]bool - subsGroup sync.WaitGroup blockSubs int executionSubs int notificationSubs int From 99108c620f6838ce14a164331c9b38edeac6c4d7 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 20:14:35 +0300 Subject: [PATCH 20/34] network: fix errcheck warning --- pkg/network/server.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/network/server.go b/pkg/network/server.go index 3e5d00808..2303b5be9 100644 --- a/pkg/network/server.go +++ b/pkg/network/server.go @@ -862,7 +862,7 @@ func (s *Server) handleP2PNotaryRequestCmd(r *payload.P2PNotaryRequest) error { } // It's OK for it to fail for various reasons like request already existing // in the pool. - s.RelayP2PNotaryRequest(r) + _ = s.RelayP2PNotaryRequest(r) return nil } From 4caff35e73083945a1751b15c95dea35d98f0835 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 20:14:52 +0300 Subject: [PATCH 21/34] consensus: fix error checking in decoders Spotted by errcheck. --- pkg/consensus/consensus.go | 15 ++++++--------- pkg/consensus/payload.go | 4 +++- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/pkg/consensus/consensus.go b/pkg/consensus/consensus.go index b6cb8cc07..9bb26483a 100644 --- a/pkg/consensus/consensus.go +++ b/pkg/consensus/consensus.go @@ -373,7 +373,12 @@ func (s *service) payloadFromExtensible(ep *npayload.Extensible) *Payload { func (s *service) OnPayload(cp *npayload.Extensible) { log := s.log.With(zap.Stringer("hash", cp.Hash())) p := s.payloadFromExtensible(cp) - p.decodeData() + // decode payload data into message + if err := p.decodeData(); err != nil { + log.Info("can't decode payload data", zap.Error(err)) + return + } + if !s.validatePayload(p) { log.Info("can't validate payload") return @@ -384,14 +389,6 @@ func (s *service) OnPayload(cp *npayload.Extensible) { return } - // decode payload data into message - if p.message.payload == nil { - if err := p.decodeData(); err != nil { - log.Info("can't decode payload data") - return - } - } - s.messages <- *p } diff --git a/pkg/consensus/payload.go b/pkg/consensus/payload.go index f06d0a54c..2d17938ea 100644 --- a/pkg/consensus/payload.go +++ b/pkg/consensus/payload.go @@ -151,7 +151,9 @@ func (p *Payload) Hash() util.Uint256 { // DecodeBinary implements io.Serializable interface. func (p *Payload) DecodeBinary(r *io.BinReader) { p.Extensible.DecodeBinary(r) - p.decodeData() + if r.Err == nil { + r.Err = p.decodeData() + } } // EncodeBinary implements io.Serializable interface. From f1f30fd0c51bb6ec225aca1bdea0d24d8492afc9 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 20:18:11 +0300 Subject: [PATCH 22/34] gendump: fix errcheck warning scripts/gendump/main.go:95:13: Error return value of `rand.Read` is not checked (errcheck) rand.Read(key) ^ scripts/gendump/main.go:96:13: Error return value of `rand.Read` is not checked (errcheck) rand.Read(value) ^ --- scripts/gendump/main.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/scripts/gendump/main.go b/scripts/gendump/main.go index 879059726..15712d532 100644 --- a/scripts/gendump/main.go +++ b/scripts/gendump/main.go @@ -92,8 +92,10 @@ func main() { txs := make([]*transaction.Transaction, txNum) for j := 0; j < txNum; j++ { nonce++ - rand.Read(key) - rand.Read(value) + _, err = rand.Read(key) + handleError("can't get random data for key", err) + _, err = rand.Read(value) + handleError("can't get random data for value", err) w := io.NewBufBinWriter() emit.AppCall(w.BinWriter, contractHash, "put", callflag.All, key, value) From 0500c8f9d72d7524ceb47026a46896a02c975ed5 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 20:19:24 +0300 Subject: [PATCH 23/34] cli/wallet: fix error handling cli/wallet/wallet.go:527:19: Error return value of `cli.NewExitError` is not checked (errcheck) cli.NewExitError("valid account address must be provided", 1) --- cli/wallet/wallet.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/wallet/wallet.go b/cli/wallet/wallet.go index 82e165925..89df95be0 100644 --- a/cli/wallet/wallet.go +++ b/cli/wallet/wallet.go @@ -524,7 +524,7 @@ func removeAccount(ctx *cli.Context) error { addr := ctx.Generic("address").(*flags.Address) if !addr.IsSet { - cli.NewExitError("valid account address must be provided", 1) + return cli.NewExitError("valid account address must be provided", 1) } acc := wall.GetAccount(addr.Uint160()) if acc == nil { From e9cefc4bfc3ce92bb1d724659e339737f645a389 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 21:34:07 +0300 Subject: [PATCH 24/34] *: fix all errcheck warnings in testing code --- cli/contract_test.go | 3 ++- cli/server/server_test.go | 24 ++++++++++++------- cli/smartcontract/smart_contract_test.go | 6 +++-- pkg/core/native/management_test.go | 3 ++- pkg/core/native_neo_test.go | 3 ++- pkg/core/native_notary_test.go | 3 ++- pkg/core/notary_test.go | 3 ++- pkg/rpc/client/rpc_test.go | 6 +++-- pkg/rpc/client/wsclient_test.go | 9 ++++--- pkg/rpc/server/client_test.go | 30 +++++++++++++----------- pkg/rpc/server/server_test.go | 14 ++++++----- pkg/rpc/server/subscription_test.go | 26 ++++++++++---------- 12 files changed, 78 insertions(+), 52 deletions(-) diff --git a/cli/contract_test.go b/cli/contract_test.go index 0dd20b12a..06bcf8551 100644 --- a/cli/contract_test.go +++ b/cli/contract_test.go @@ -403,7 +403,8 @@ func TestComlileAndInvokeFunction(t *testing.T) { require.NoError(t, err) pk, err := keys.NewPrivateKey() require.NoError(t, err) - acc.ConvertMultisig(2, keys.PublicKeys{acc.PrivateKey().PublicKey(), pk.PublicKey()}) + err = acc.ConvertMultisig(2, keys.PublicKeys{acc.PrivateKey().PublicKey(), pk.PublicKey()}) + require.NoError(t, err) t.Run("cosigner is multisig account", func(t *testing.T) { t.Run("missing in the wallet", func(t *testing.T) { diff --git a/cli/server/server_test.go b/cli/server/server_test.go index 5f0184550..f3bb25fee 100644 --- a/cli/server/server_test.go +++ b/cli/server/server_test.go @@ -62,9 +62,11 @@ func TestHandleLoggingParams(t *testing.T) { func TestInitBCWithMetrics(t *testing.T) { d, err := ioutil.TempDir("./", "") require.NoError(t, err) - os.Chdir(d) + err = os.Chdir(d) + require.NoError(t, err) t.Cleanup(func() { - os.Chdir("..") + err = os.Chdir("..") + require.NoError(t, err) os.RemoveAll(d) }) @@ -91,9 +93,11 @@ func TestDumpDB(t *testing.T) { t.Run("too low chain", func(t *testing.T) { d, err := ioutil.TempDir("./", "") require.NoError(t, err) - os.Chdir(d) + err = os.Chdir(d) + require.NoError(t, err) t.Cleanup(func() { - os.Chdir("..") + err = os.Chdir("..") + require.NoError(t, err) os.RemoveAll(d) }) testDump := "file.acc" @@ -112,9 +116,11 @@ func TestDumpDB(t *testing.T) { t.Run("positive", func(t *testing.T) { d, err := ioutil.TempDir("./", "") require.NoError(t, err) - os.Chdir(d) + err = os.Chdir(d) + require.NoError(t, err) t.Cleanup(func() { - os.Chdir("..") + err = os.Chdir("..") + require.NoError(t, err) os.RemoveAll(d) }) testDump := "file.acc" @@ -136,9 +142,11 @@ func TestRestoreDB(t *testing.T) { require.NoError(t, err) testDump := "file1.acc" saveDump := "file2.acc" - os.Chdir(d) + err = os.Chdir(d) + require.NoError(t, err) t.Cleanup(func() { - os.Chdir("..") + err = os.Chdir("..") + require.NoError(t, err) os.RemoveAll(d) }) diff --git a/cli/smartcontract/smart_contract_test.go b/cli/smartcontract/smart_contract_test.go index 3dfbb298c..a85b8eff2 100644 --- a/cli/smartcontract/smart_contract_test.go +++ b/cli/smartcontract/smart_contract_test.go @@ -13,9 +13,11 @@ import ( func TestInitSmartContract(t *testing.T) { d, err := ioutil.TempDir("./", "") require.NoError(t, err) - os.Chdir(d) + err = os.Chdir(d) + require.NoError(t, err) t.Cleanup(func() { - os.Chdir("..") + err = os.Chdir("..") + require.NoError(t, err) os.RemoveAll(d) }) contractName := "testContract" diff --git a/pkg/core/native/management_test.go b/pkg/core/native/management_test.go index d8e619fe1..fedb9ed0e 100644 --- a/pkg/core/native/management_test.go +++ b/pkg/core/native/management_test.go @@ -18,7 +18,8 @@ import ( func TestDeployGetUpdateDestroyContract(t *testing.T) { mgmt := newManagement() d := dao.NewCached(dao.NewSimple(storage.NewMemoryStore(), false)) - mgmt.Initialize(&interop.Context{DAO: d}) + err := mgmt.Initialize(&interop.Context{DAO: d}) + require.NoError(t, err) script := []byte{byte(opcode.RET)} sender := util.Uint160{1, 2, 3} ne, err := nef.NewFile(script) diff --git a/pkg/core/native_neo_test.go b/pkg/core/native_neo_test.go index b085ba824..19207137b 100644 --- a/pkg/core/native_neo_test.go +++ b/pkg/core/native_neo_test.go @@ -122,7 +122,8 @@ func TestNEO_Vote(t *testing.T) { ic.VM.Load(priv.PublicKey().GetVerificationScript()) require.NoError(t, neo.VoteInternal(ic, h, candidates[0])) - ic.DAO.Persist() + _, err = ic.DAO.Persist() + require.NoError(t, err) advanceChain(t) pubs, err = neo.ComputeNextBlockValidators(bc, ic.DAO) require.NoError(t, err) diff --git a/pkg/core/native_notary_test.go b/pkg/core/native_notary_test.go index 1eed3a19c..22d17f1e7 100644 --- a/pkg/core/native_notary_test.go +++ b/pkg/core/native_notary_test.go @@ -208,7 +208,8 @@ func TestNotaryContractPipeline(t *testing.T) { checkResult(t, balance, stackitem.Make(3*transaction.NotaryServiceFeePerKey)) // `withdraw`: unlock deposit and transfer GAS back to owner - chain.genBlocks(depositLock) + _, err = chain.genBlocks(depositLock) + require.NoError(t, err) withdrawRes, err = invokeContractMethod(chain, 100000000, notaryHash, "withdraw", testchain.MultisigScriptHash(), testchain.MultisigScriptHash()) require.NoError(t, err) checkResult(t, withdrawRes, stackitem.NewBool(true)) diff --git a/pkg/core/notary_test.go b/pkg/core/notary_test.go index 35c18fa50..ebdea6f0d 100644 --- a/pkg/core/notary_test.go +++ b/pkg/core/notary_test.go @@ -145,7 +145,8 @@ func TestNotary(t *testing.T) { VerificationScript: []byte{}, }, } - requester.SignTx(testchain.Network(), fallback) + err = requester.SignTx(testchain.Network(), fallback) + require.NoError(t, err) return fallback } diff --git a/pkg/rpc/client/rpc_test.go b/pkg/rpc/client/rpc_test.go index 3d7cde863..ea74a0276 100644 --- a/pkg/rpc/client/rpc_test.go +++ b/pkg/rpc/client/rpc_test.go @@ -1539,7 +1539,8 @@ func initTestServer(t *testing.T, resp string) *httptest.Server { ws, err := upgrader.Upgrade(w, req, nil) require.NoError(t, err) for { - ws.SetReadDeadline(time.Now().Add(2 * time.Second)) + err = ws.SetReadDeadline(time.Now().Add(2 * time.Second)) + require.NoError(t, err) _, p, err := ws.ReadMessage() if err != nil { break @@ -1550,7 +1551,8 @@ func initTestServer(t *testing.T, resp string) *httptest.Server { t.Fatalf("Cannot decode request body: %s", req.Body) } response := wrapInitResponse(r, resp) - ws.SetWriteDeadline(time.Now().Add(2 * time.Second)) + err = ws.SetWriteDeadline(time.Now().Add(2 * time.Second)) + require.NoError(t, err) err = ws.WriteMessage(1, []byte(response)) if err != nil { break diff --git a/pkg/rpc/client/wsclient_test.go b/pkg/rpc/client/wsclient_test.go index 61b1cd9c7..24b2dc4a8 100644 --- a/pkg/rpc/client/wsclient_test.go +++ b/pkg/rpc/client/wsclient_test.go @@ -128,7 +128,8 @@ func TestWSClientEvents(t *testing.T) { ws, err := upgrader.Upgrade(w, req, nil) require.NoError(t, err) for _, event := range events { - ws.SetWriteDeadline(time.Now().Add(2 * time.Second)) + err = ws.SetWriteDeadline(time.Now().Add(2 * time.Second)) + require.NoError(t, err) err = ws.WriteMessage(1, []byte(event)) if err != nil { break @@ -313,14 +314,16 @@ func TestWSFilteredSubscriptions(t *testing.T) { var upgrader = websocket.Upgrader{} ws, err := upgrader.Upgrade(w, req, nil) require.NoError(t, err) - ws.SetReadDeadline(time.Now().Add(2 * time.Second)) + err = ws.SetReadDeadline(time.Now().Add(2 * time.Second)) + require.NoError(t, err) req := request.In{} err = ws.ReadJSON(&req) require.NoError(t, err) params, err := req.Params() require.NoError(t, err) c.serverCode(t, params) - ws.SetWriteDeadline(time.Now().Add(2 * time.Second)) + err = ws.SetWriteDeadline(time.Now().Add(2 * time.Second)) + require.NoError(t, err) err = ws.WriteMessage(1, []byte(`{"jsonrpc": "2.0", "id": 1, "result": "0"}`)) require.NoError(t, err) ws.Close() diff --git a/pkg/rpc/server/client_test.go b/pkg/rpc/server/client_test.go index fcabd560d..15fd37d37 100644 --- a/pkg/rpc/server/client_test.go +++ b/pkg/rpc/server/client_test.go @@ -31,7 +31,7 @@ import ( func TestClient_NEP17(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) require.NoError(t, err) @@ -74,7 +74,7 @@ func TestClient_NEP17(t *testing.T) { func TestAddNetworkFeeCalculateNetworkFee(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() const extraFee = 10 var nonce uint32 @@ -156,12 +156,13 @@ func TestAddNetworkFeeCalculateNetworkFee(t *testing.T) { t.Run("Multi", func(t *testing.T) { acc0 := wallet.NewAccountFromPrivateKey(testchain.PrivateKeyByID(0)) acc1 := wallet.NewAccountFromPrivateKey(testchain.PrivateKeyByID(0)) - acc1.ConvertMultisig(3, keys.PublicKeys{ + err = acc1.ConvertMultisig(3, keys.PublicKeys{ testchain.PrivateKeyByID(0).PublicKey(), testchain.PrivateKeyByID(1).PublicKey(), testchain.PrivateKeyByID(2).PublicKey(), testchain.PrivateKeyByID(3).PublicKey(), }) + require.NoError(t, err) check := func(t *testing.T, extraFee int64) { tx := transaction.New([]byte{byte(opcode.PUSH1)}, 0) tx.ValidUntilBlock = 20 @@ -322,7 +323,7 @@ func TestAddNetworkFeeCalculateNetworkFee(t *testing.T) { func TestCalculateNetworkFee(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() const extraFee = 10 c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) @@ -392,7 +393,7 @@ func TestCalculateNetworkFee(t *testing.T) { func TestSignAndPushInvocationTx(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) require.NoError(t, err) @@ -549,7 +550,7 @@ func TestSignAndPushInvocationTx(t *testing.T) { func TestSignAndPushP2PNotaryRequest(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChainAndServices(t, false, true) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) require.NoError(t, err) @@ -620,7 +621,8 @@ func TestSignAndPushP2PNotaryRequest(t *testing.T) { w, err := wallet.NewWalletFromFile(notaryPath) require.NoError(t, err) ntr := w.Accounts[0] - ntr.Decrypt(notaryPass) + err = ntr.Decrypt(notaryPass) + require.NoError(t, err) req.FallbackTransaction.Scripts[0] = transaction.Witness{ InvocationScript: append([]byte{byte(opcode.PUSHDATA1), 64}, ntr.PrivateKey().SignHashable(uint32(testchain.Network()), req.FallbackTransaction)...), VerificationScript: []byte{}, @@ -639,7 +641,7 @@ func TestSignAndPushP2PNotaryRequest(t *testing.T) { func TestCalculateNotaryFee(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) require.NoError(t, err) @@ -667,7 +669,7 @@ func TestPing(t *testing.T) { func TestCreateTxFromScript(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) require.NoError(t, err) @@ -696,7 +698,7 @@ func TestCreateTxFromScript(t *testing.T) { func TestCreateNEP17TransferTx(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) require.NoError(t, err) @@ -720,7 +722,7 @@ func TestCreateNEP17TransferTx(t *testing.T) { func TestInvokeVerify(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) require.NoError(t, err) @@ -762,7 +764,7 @@ func TestInvokeVerify(t *testing.T) { func TestClient_GetNativeContracts(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) require.NoError(t, err) @@ -776,7 +778,7 @@ func TestClient_GetNativeContracts(t *testing.T) { func TestClient_NEP11(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) require.NoError(t, err) @@ -842,7 +844,7 @@ func TestClient_NEP11(t *testing.T) { func TestClient_NNS(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() c, err := client.New(context.Background(), httpSrv.URL, client.Options{}) require.NoError(t, err) diff --git a/pkg/rpc/server/server_test.go b/pkg/rpc/server/server_test.go index fc06ebcc3..804426b34 100644 --- a/pkg/rpc/server/server_test.go +++ b/pkg/rpc/server/server_test.go @@ -1010,7 +1010,7 @@ func TestRPC(t *testing.T) { func TestSubmitOracle(t *testing.T) { chain, rpcSrv, httpSrv := initClearServerWithServices(t, true, false) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() rpc := `{"jsonrpc": "2.0", "id": 1, "method": "submitoracleresponse", "params": %s}` runCase := func(t *testing.T, fail bool, params ...string) func(t *testing.T) { @@ -1046,7 +1046,7 @@ func TestSubmitNotaryRequest(t *testing.T) { t.Run("disabled P2PSigExtensions", func(t *testing.T) { chain, rpcSrv, httpSrv := initClearServerWithServices(t, false, false) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() req := fmt.Sprintf(rpc, "[]") body := doRPCCallOverHTTP(req, httpSrv.URL, t) checkErrGetResult(t, body, true) @@ -1054,7 +1054,7 @@ func TestSubmitNotaryRequest(t *testing.T) { chain, rpcSrv, httpSrv := initServerWithInMemoryChainAndServices(t, false, true) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() runCase := func(t *testing.T, fail bool, params ...string) func(t *testing.T) { return func(t *testing.T) { @@ -1156,7 +1156,7 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() e := &executor{chain: chain, httpSrv: httpSrv} t.Run("single request", func(t *testing.T) { @@ -1595,9 +1595,11 @@ func doRPCCallOverWS(rpcCall string, url string, t *testing.T) []byte { url = "ws" + strings.TrimPrefix(url, "http") c, _, err := dialer.Dial(url+"/ws", nil) require.NoError(t, err) - c.SetWriteDeadline(time.Now().Add(time.Second)) + err = c.SetWriteDeadline(time.Now().Add(time.Second)) + require.NoError(t, err) require.NoError(t, c.WriteMessage(1, []byte(rpcCall))) - c.SetReadDeadline(time.Now().Add(time.Second)) + err = c.SetReadDeadline(time.Now().Add(time.Second)) + require.NoError(t, err) _, body, err := c.ReadMessage() require.NoError(t, err) require.NoError(t, c.Close()) diff --git a/pkg/rpc/server/subscription_test.go b/pkg/rpc/server/subscription_test.go index 7f8872eed..9fe6ceafc 100644 --- a/pkg/rpc/server/subscription_test.go +++ b/pkg/rpc/server/subscription_test.go @@ -20,7 +20,8 @@ const testOverflow = false func wsReader(t *testing.T, ws *websocket.Conn, msgCh chan<- []byte, isFinished *atomic.Bool) { for { - ws.SetReadDeadline(time.Now().Add(time.Second)) + err := ws.SetReadDeadline(time.Now().Add(time.Second)) + require.NoError(t, err) _, body, err := ws.ReadMessage() if isFinished.Load() { require.Error(t, err) @@ -34,7 +35,7 @@ func wsReader(t *testing.T, ws *websocket.Conn, msgCh chan<- []byte, isFinished func callWSGetRaw(t *testing.T, ws *websocket.Conn, msg string, respCh <-chan []byte) *response.Raw { var resp = new(response.Raw) - ws.SetWriteDeadline(time.Now().Add(time.Second)) + require.NoError(t, ws.SetWriteDeadline(time.Now().Add(time.Second))) require.NoError(t, ws.WriteMessage(websocket.TextMessage, []byte(msg))) body := <-respCh @@ -90,7 +91,7 @@ func TestSubscriptions(t *testing.T) { chain, rpcSrv, c, respMsgs, finishedFlag := initCleanServerAndWSClient(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() for _, feed := range subFeeds { s := callSubscribe(t, c, respMsgs, fmt.Sprintf(`["%s"]`, feed)) @@ -243,7 +244,7 @@ func TestFilteredSubscriptions(t *testing.T) { chain, rpcSrv, c, respMsgs, finishedFlag := initCleanServerAndWSClient(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() // It's used as an end-of-event-stream, so it's always present. blockSubID := callSubscribe(t, c, respMsgs, `["block_added"]`) @@ -283,7 +284,7 @@ func TestFilteredBlockSubscriptions(t *testing.T) { chain, rpcSrv, c, respMsgs, finishedFlag := initCleanServerAndWSClient(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() blockSubID := callSubscribe(t, c, respMsgs, `["block_added", {"primary":3}]`) @@ -322,7 +323,7 @@ func TestMaxSubscriptions(t *testing.T) { chain, rpcSrv, c, respMsgs, finishedFlag := initCleanServerAndWSClient(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() for i := 0; i < maxFeeds+1; i++ { var s string @@ -368,7 +369,7 @@ func TestBadSubUnsub(t *testing.T) { chain, rpcSrv, c, respMsgs, finishedFlag := initCleanServerAndWSClient(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() testF := func(t *testing.T, cases map[string]string) func(t *testing.T) { return func(t *testing.T) { @@ -389,19 +390,20 @@ func TestBadSubUnsub(t *testing.T) { } func doSomeWSRequest(t *testing.T, ws *websocket.Conn) { - ws.SetWriteDeadline(time.Now().Add(time.Second)) + require.NoError(t, ws.SetWriteDeadline(time.Now().Add(time.Second))) // It could be just about anything including invalid request, // we only care about server handling being active. require.NoError(t, ws.WriteMessage(websocket.TextMessage, []byte(`{"jsonrpc": "2.0", "method": "getversion", "params": [], "id": 1}`))) - ws.SetReadDeadline(time.Now().Add(time.Second)) - _, _, err := ws.ReadMessage() + err := ws.SetReadDeadline(time.Now().Add(time.Second)) + require.NoError(t, err) + _, _, err = ws.ReadMessage() require.NoError(t, err) } func TestWSClientsLimit(t *testing.T) { chain, rpcSrv, httpSrv := initClearServerWithInMemoryChain(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() dialer := websocket.Dialer{HandshakeTimeout: time.Second} url := "ws" + strings.TrimPrefix(httpSrv.URL, "http") + "/ws" @@ -440,7 +442,7 @@ func TestSubscriptionOverflow(t *testing.T) { chain, rpcSrv, c, respMsgs, finishedFlag := initCleanServerAndWSClient(t) defer chain.Close() - defer rpcSrv.Shutdown() + defer func() { _ = rpcSrv.Shutdown() }() resp := callWSGetRaw(t, c, `{"jsonrpc": "2.0","method": "subscribe","params": ["block_added"],"id": 1}`, respMsgs) require.Nil(t, resp.Error) From a44376903a46c81b8a13a1929e3927131544ac56 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 21:45:32 +0300 Subject: [PATCH 25/34] rpc: fix errcheck warnings in websocket code --- pkg/rpc/client/wsclient.go | 17 ++++++++++++----- pkg/rpc/server/server.go | 18 ++++++++++++------ 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/pkg/rpc/client/wsclient.go b/pkg/rpc/client/wsclient.go index 7ff486246..8a8e4824f 100644 --- a/pkg/rpc/client/wsclient.go +++ b/pkg/rpc/client/wsclient.go @@ -114,12 +114,15 @@ func (c *WSClient) Close() { func (c *WSClient) wsReader() { c.ws.SetReadLimit(wsReadLimit) - c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(wsPongLimit)); return nil }) + c.ws.SetPongHandler(func(string) error { return c.ws.SetReadDeadline(time.Now().Add(wsPongLimit)) }) readloop: for { rr := new(requestResponse) - c.ws.SetReadDeadline(time.Now().Add(wsPongLimit)) - err := c.ws.ReadJSON(rr) + err := c.ws.SetReadDeadline(time.Now().Add(wsPongLimit)) + if err != nil { + break + } + err = c.ws.ReadJSON(rr) if err != nil { // Timeout/connection loss/malformed response. break @@ -191,12 +194,16 @@ func (c *WSClient) wsWriter() { if !ok { return } - c.ws.SetWriteDeadline(time.Now().Add(c.opts.RequestTimeout)) + if err := c.ws.SetWriteDeadline(time.Now().Add(c.opts.RequestTimeout)); err != nil { + return + } if err := c.ws.WriteJSON(req); err != nil { return } case <-pingTicker.C: - c.ws.SetWriteDeadline(time.Now().Add(wsWriteLimit)) + if err := c.ws.SetWriteDeadline(time.Now().Add(wsWriteLimit)); err != nil { + return + } if err := c.ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil { return } diff --git a/pkg/rpc/server/server.go b/pkg/rpc/server/server.go index ab3e5bca7..085329474 100644 --- a/pkg/rpc/server/server.go +++ b/pkg/rpc/server/server.go @@ -359,7 +359,9 @@ eventloop: if !ok { break eventloop } - ws.SetWriteDeadline(time.Now().Add(wsWriteLimit)) + if err := ws.SetWriteDeadline(time.Now().Add(wsWriteLimit)); err != nil { + break eventloop + } if err := ws.WritePreparedMessage(event); err != nil { break eventloop } @@ -367,12 +369,16 @@ eventloop: if !ok { break eventloop } - ws.SetWriteDeadline(time.Now().Add(wsWriteLimit)) + if err := ws.SetWriteDeadline(time.Now().Add(wsWriteLimit)); err != nil { + break eventloop + } if err := ws.WriteJSON(res); err != nil { break eventloop } case <-pingTicker.C: - ws.SetWriteDeadline(time.Now().Add(wsWriteLimit)) + if err := ws.SetWriteDeadline(time.Now().Add(wsWriteLimit)); err != nil { + break eventloop + } if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil { break eventloop } @@ -397,10 +403,10 @@ drainloop: func (s *Server) handleWsReads(ws *websocket.Conn, resChan chan<- response.AbstractResult, subscr *subscriber) { ws.SetReadLimit(wsReadLimit) - ws.SetReadDeadline(time.Now().Add(wsPongLimit)) - ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(wsPongLimit)); return nil }) + err := ws.SetReadDeadline(time.Now().Add(wsPongLimit)) + ws.SetPongHandler(func(string) error { return ws.SetReadDeadline(time.Now().Add(wsPongLimit)) }) requestloop: - for { + for err == nil { req := request.NewRequest() err := ws.ReadJSON(req) if err != nil { From b1710bebaaba519d8412d0c733cca00f011eab11 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 21:49:42 +0300 Subject: [PATCH 26/34] native: fix errcheck errors in nns contract --- pkg/core/native/name_service.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/core/native/name_service.go b/pkg/core/native/name_service.go index 0044624d3..7e3893f90 100644 --- a/pkg/core/native/name_service.go +++ b/pkg/core/native/name_service.go @@ -565,7 +565,7 @@ func (s *nameState) EncodeBinary(w *io.BinWriter) { func (s *nameState) DecodeBinary(r *io.BinReader) { item := stackitem.DecodeBinaryStackItem(r) if r.Err == nil { - s.FromStackItem(item) + r.Err = s.FromStackItem(item) } } @@ -700,7 +700,7 @@ func (sl stringList) EncodeBinary(w *io.BinWriter) { func (sl *stringList) DecodeBinary(r *io.BinReader) { item := stackitem.DecodeBinaryStackItem(r) if r.Err == nil { - sl.FromStackItem(item) + r.Err = sl.FromStackItem(item) } } From 6fea16451a940eacc84b6a4071b4d18ab1c9e54e Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 21:53:41 +0300 Subject: [PATCH 27/34] cli/input: ignore term.Restore errors, fix errcheck warnings I'm not sure we can do anything useful here. --- cli/input/input.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cli/input/input.go b/cli/input/input.go index fa61dee10..ee62a531a 100644 --- a/cli/input/input.go +++ b/cli/input/input.go @@ -25,7 +25,7 @@ func ReadLine(prompt string) (string, error) { if err != nil { panic(err) } - defer term.Restore(syscall.Stdin, s) + defer func() { _ = term.Restore(syscall.Stdin, s) }() trm = term.NewTerminal(ReadWriter{ Reader: os.Stdin, Writer: os.Stdout, @@ -50,7 +50,7 @@ func ReadPassword(prompt string) (string, error) { if err != nil { panic(err) } - defer term.Restore(syscall.Stdin, s) + defer func() { _ = term.Restore(syscall.Stdin, s) }() trm = term.NewTerminal(ReadWriter{os.Stdin, os.Stdout}, prompt) } return trm.ReadPassword(prompt) From c4e084b0d857f7f11e489a55e21ee3065b4bc18a Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 22:51:41 +0300 Subject: [PATCH 28/34] *: fix whitespace errors leading/trailing newlines --- cli/wallet/legacy.go | 1 - cli/wallet/legacy_test.go | 1 - cli/wallet/nep11.go | 1 - internal/testchain/transaction.go | 1 - pkg/compiler/codegen.go | 1 - pkg/compiler/vm_test.go | 1 - pkg/consensus/consensus.go | 1 - pkg/core/block/block_test.go | 1 - pkg/core/blockchain.go | 1 - pkg/core/blockchain_test.go | 1 - pkg/core/mpt/batch.go | 1 - pkg/core/native/management.go | 1 - pkg/core/native/name_service.go | 1 - pkg/core/native/native_neo.go | 1 - pkg/core/native/util.go | 1 - pkg/core/native_designate_test.go | 1 - pkg/core/native_management_test.go | 1 - pkg/core/native_name_service_test.go | 1 - pkg/core/native_neo_test.go | 1 - pkg/core/state/notification_event_test.go | 1 - pkg/core/state/oracle_test.go | 1 - pkg/crypto/keys/nep2_test.go | 1 - pkg/crypto/keys/publickey.go | 1 - pkg/encoding/fixedn/fixed8_test.go | 1 - pkg/io/binaryWriter.go | 1 - pkg/network/payload/getblocks.go | 1 - pkg/network/server.go | 1 - pkg/network/server_test.go | 1 - pkg/rpc/client/wsclient.go | 1 - pkg/rpc/response/errors.go | 1 - pkg/rpc/server/server.go | 1 - pkg/rpc/server/server_test.go | 1 - pkg/rpc/server/subscription_test.go | 1 - pkg/services/oracle/neofs/neofs_test.go | 1 - pkg/services/oracle/transaction.go | 1 - pkg/vm/vm_test.go | 1 - 36 files changed, 36 deletions(-) diff --git a/cli/wallet/legacy.go b/cli/wallet/legacy.go index 3ddbd6e5f..bace1cef9 100644 --- a/cli/wallet/legacy.go +++ b/cli/wallet/legacy.go @@ -156,7 +156,6 @@ func parseMultisigContract(script []byte) (int, keys.PublicKeys, bool) { return 0, nil, false } ret[i] = pub - } return nsigs, ret, true } diff --git a/cli/wallet/legacy_test.go b/cli/wallet/legacy_test.go index af952fff5..7195bc81a 100644 --- a/cli/wallet/legacy_test.go +++ b/cli/wallet/legacy_test.go @@ -94,7 +94,6 @@ func TestParseMultisigContract(t *testing.T) { } }) }) - } func fromHex(t *testing.T, s string) []byte { diff --git a/cli/wallet/nep11.go b/cli/wallet/nep11.go index fe92ce857..7481fdb6f 100644 --- a/cli/wallet/nep11.go +++ b/cli/wallet/nep11.go @@ -226,7 +226,6 @@ func getNEP11Balance(ctx *cli.Context) error { } fmt.Fprintf(ctx.App.Writer, format, formatArgs...) fmt.Fprintf(ctx.App.Writer, "\tAmount : %s\n", amountStr) - } return nil } diff --git a/internal/testchain/transaction.go b/internal/testchain/transaction.go index 04363f7cd..bf8cfc685 100644 --- a/internal/testchain/transaction.go +++ b/internal/testchain/transaction.go @@ -79,7 +79,6 @@ func NewDeployTx(bc blockchainer.Blockchainer, name string, sender util.Uint160, o.ContractEvents = conf.Events o.ContractSupportedStandards = conf.SupportedStandards o.SafeMethods = conf.SafeMethods - } m, err := compiler.CreateManifest(di, o) if err != nil { diff --git a/pkg/compiler/codegen.go b/pkg/compiler/codegen.go index f80311da5..14a456165 100644 --- a/pkg/compiler/codegen.go +++ b/pkg/compiler/codegen.go @@ -473,7 +473,6 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor { return nil } switch n := node.(type) { - // General declarations. // var ( // x = 2 diff --git a/pkg/compiler/vm_test.go b/pkg/compiler/vm_test.go index 4752ef708..6545dcf73 100644 --- a/pkg/compiler/vm_test.go +++ b/pkg/compiler/vm_test.go @@ -109,7 +109,6 @@ func newStoragePlugin() *storagePlugin { s.interops[interopnames.ToID([]byte(interopnames.SystemRuntimeNotify))] = s.Notify s.interops[interopnames.ToID([]byte(interopnames.SystemRuntimeGetTime))] = s.GetTime return s - } func (s *storagePlugin) syscallHandler(v *vm.VM, id uint32) error { diff --git a/pkg/consensus/consensus.go b/pkg/consensus/consensus.go index 9bb26483a..3321bb8c0 100644 --- a/pkg/consensus/consensus.go +++ b/pkg/consensus/consensus.go @@ -309,7 +309,6 @@ events: s.handleChainBlock(b) default: } - } close(s.finished) } diff --git a/pkg/core/block/block_test.go b/pkg/core/block/block_test.go index b8042f3ef..834ca0620 100644 --- a/pkg/core/block/block_test.go +++ b/pkg/core/block/block_test.go @@ -239,7 +239,6 @@ func TestBlockEncodeDecode(t *testing.T) { func TestGetExpectedBlockSize(t *testing.T) { check := func(t *testing.T, stateRootEnabled bool) { - t.Run("without transactions", func(t *testing.T) { b := newDumbBlock() b.StateRootEnabled = stateRootEnabled diff --git a/pkg/core/blockchain.go b/pkg/core/blockchain.go index 566626c63..9aeb78a93 100644 --- a/pkg/core/blockchain.go +++ b/pkg/core/blockchain.go @@ -1600,7 +1600,6 @@ func (bc *Blockchain) IsTxStillRelevant(t *transaction.Transaction, txpool *memp return bc.verifyTxWitnesses(t, nil, isPartialTx) == nil } return true - } // VerifyTx verifies whether transaction is bonafide or not relative to the diff --git a/pkg/core/blockchain_test.go b/pkg/core/blockchain_test.go index 3bbf4b043..6393016d1 100644 --- a/pkg/core/blockchain_test.go +++ b/pkg/core/blockchain_test.go @@ -1529,7 +1529,6 @@ func testDumpAndRestore(t *testing.T, dumpF, restoreF func(c *config.Config)) { require.Equal(t, bc.BlockHeight()-1, lastIndex) }) }) - } func TestDumpAndRestore(t *testing.T) { diff --git a/pkg/core/mpt/batch.go b/pkg/core/mpt/batch.go index 7a9409151..5c9287413 100644 --- a/pkg/core/mpt/batch.go +++ b/pkg/core/mpt/batch.go @@ -208,7 +208,6 @@ func (t *Trie) newSubTrieMany(prefix []byte, kv []keyValue, value []byte) (Node, if len(kv[0].value) == 0 { if len(kv) == 1 { return new(HashNode), 1, nil - } node, n, err := t.newSubTrieMany(prefix, kv[1:], nil) return node, n + 1, err diff --git a/pkg/core/native/management.go b/pkg/core/native/management.go index 2a1bc77d5..01aeab5b5 100644 --- a/pkg/core/native/management.go +++ b/pkg/core/native/management.go @@ -539,7 +539,6 @@ func (m *Management) getNextContractID(d dao.DAO) (int32, error) { si := d.GetStorageItem(m.ID, keyNextAvailableID) if si == nil { return 0, errors.New("nextAvailableID is not initialized") - } id := bigint.FromBytes(si) ret := int32(id.Int64()) diff --git a/pkg/core/native/name_service.go b/pkg/core/native/name_service.go index 7e3893f90..4116d1fbc 100644 --- a/pkg/core/native/name_service.go +++ b/pkg/core/native/name_service.go @@ -626,7 +626,6 @@ func domainFromString(name string) (string, bool) { return name, true } return name[i+1:], true - } func toDomain(name string) string { diff --git a/pkg/core/native/native_neo.go b/pkg/core/native/native_neo.go index 0580680fa..1a6af1a16 100644 --- a/pkg/core/native/native_neo.go +++ b/pkg/core/native/native_neo.go @@ -337,7 +337,6 @@ func (n *NEO) PostPersist(ic *interop.Context) error { } } } - } if n.gasPerBlockChanged.Load().(bool) { gr, err := n.getSortedGASRecordFromDAO(ic.DAO) diff --git a/pkg/core/native/util.go b/pkg/core/native/util.go index 73ac7f316..c882762cb 100644 --- a/pkg/core/native/util.go +++ b/pkg/core/native/util.go @@ -42,7 +42,6 @@ func getIntWithKey(id int32, dao dao.DAO, key []byte) int64 { si := dao.GetStorageItem(id, key) if si == nil { panic(fmt.Errorf("item with id = %d and key = %s is not initialized", id, hex.EncodeToString(key))) - } return bigint.FromBytes(si).Int64() } diff --git a/pkg/core/native_designate_test.go b/pkg/core/native_designate_test.go index 6f8bacb7f..0846a8a2c 100644 --- a/pkg/core/native_designate_test.go +++ b/pkg/core/native_designate_test.go @@ -116,7 +116,6 @@ func TestDesignate_DesignateAsRoleTx(t *testing.T) { bc.setNodesByRole(t, true, noderoles.NeoFSAlphabet, pubs) bc.getNodesByRole(t, true, noderoles.NeoFSAlphabet, bc.BlockHeight()+1, 1) }) - } func TestDesignate_DesignateAsRole(t *testing.T) { diff --git a/pkg/core/native_management_test.go b/pkg/core/native_management_test.go index b0f441e68..355a57e37 100644 --- a/pkg/core/native_management_test.go +++ b/pkg/core/native_management_test.go @@ -577,7 +577,6 @@ func TestContractDestroy(t *testing.T) { t.Run("check contract", func(t *testing.T) { checkContractState(t, bc, cs1.Hash, nil) }) - }) } diff --git a/pkg/core/native_name_service_test.go b/pkg/core/native_name_service_test.go index a428b48dc..8c394f86b 100644 --- a/pkg/core/native_name_service_test.go +++ b/pkg/core/native_name_service_test.go @@ -120,7 +120,6 @@ func TestExpiration(t *testing.T) { aer, err = bc.GetAppExecResults(tx.Hash(), trigger.Application) require.NoError(t, err) checkResult(t, &aer[0], stackitem.Null{}) - } const secondsInYear = 365 * 24 * 3600 diff --git a/pkg/core/native_neo_test.go b/pkg/core/native_neo_test.go index 19207137b..5050681da 100644 --- a/pkg/core/native_neo_test.go +++ b/pkg/core/native_neo_test.go @@ -226,7 +226,6 @@ func TestNEO_CalculateBonus(t *testing.T) { res, err := neo.CalculateNEOHolderReward(ic.DAO, big.NewInt(100), 5, 15) require.NoError(t, err) require.EqualValues(t, (100*5*5/10)+(100*5*1/10), res.Int64()) - }) } diff --git a/pkg/core/state/notification_event_test.go b/pkg/core/state/notification_event_test.go index 99defd0d9..2429b7c81 100644 --- a/pkg/core/state/notification_event_test.go +++ b/pkg/core/state/notification_event_test.go @@ -116,7 +116,6 @@ func TestMarshalUnmarshalJSONNotificationEvent(t *testing.T) { err := json.Unmarshal([]byte(errCase), new(NotificationEvent)) require.Error(t, err) } - }) } diff --git a/pkg/core/state/oracle_test.go b/pkg/core/state/oracle_test.go index 3c3a3abe2..dc0a9ed12 100644 --- a/pkg/core/state/oracle_test.go +++ b/pkg/core/state/oracle_test.go @@ -76,5 +76,4 @@ func TestOracleRequest_EncodeBinary(t *testing.T) { t.Run("Method", runInvalid(5, stackitem.NewMap())) t.Run("UserData", runInvalid(6, stackitem.NewMap())) }) - } diff --git a/pkg/crypto/keys/nep2_test.go b/pkg/crypto/keys/nep2_test.go index 218ab050a..78de1f5c6 100644 --- a/pkg/crypto/keys/nep2_test.go +++ b/pkg/crypto/keys/nep2_test.go @@ -9,7 +9,6 @@ import ( func TestNEP2Encrypt(t *testing.T) { for _, testCase := range keytestcases.Arr { - privKey, err := NewPrivateKeyFromHex(testCase.PrivateKey) if testCase.Invalid { assert.Error(t, err) diff --git a/pkg/crypto/keys/publickey.go b/pkg/crypto/keys/publickey.go index 9ff009490..a3660d616 100644 --- a/pkg/crypto/keys/publickey.go +++ b/pkg/crypto/keys/publickey.go @@ -161,7 +161,6 @@ func (p *PublicKey) getBytes(compressed bool) []byte { prefix = 0x04 yBytes := p.Y.Bytes() copy(res[1+coordLen+coordLen-len(yBytes):], yBytes) - } res[0] = prefix diff --git a/pkg/encoding/fixedn/fixed8_test.go b/pkg/encoding/fixedn/fixed8_test.go index 99ef0d74e..8498a5793 100644 --- a/pkg/encoding/fixedn/fixed8_test.go +++ b/pkg/encoding/fixedn/fixed8_test.go @@ -31,7 +31,6 @@ func TestFixed8Add(t *testing.T) { } func TestFixed8Sub(t *testing.T) { - a := Fixed8FromInt64(42) b := Fixed8FromInt64(34) diff --git a/pkg/io/binaryWriter.go b/pkg/io/binaryWriter.go index 9785b0449..5ad499988 100644 --- a/pkg/io/binaryWriter.go +++ b/pkg/io/binaryWriter.go @@ -119,7 +119,6 @@ func (w *BinWriter) WriteVarUint(val uint64) { w.WriteB(byte(0xfe)) w.WriteU32LE(uint32(val)) return - } w.WriteB(byte(0xff)) diff --git a/pkg/network/payload/getblocks.go b/pkg/network/payload/getblocks.go index 8a0bf0a56..e3434ebce 100644 --- a/pkg/network/payload/getblocks.go +++ b/pkg/network/payload/getblocks.go @@ -34,7 +34,6 @@ func (p *GetBlocks) DecodeBinary(br *io.BinReader) { if p.Count < -1 || p.Count == 0 { br.Err = errors.New("invalid count") } - } // EncodeBinary implements Serializable interface. diff --git a/pkg/network/server.go b/pkg/network/server.go index 2303b5be9..560829d5d 100644 --- a/pkg/network/server.go +++ b/pkg/network/server.go @@ -409,7 +409,6 @@ func (s *Server) run() { // because we have two goroutines sending signals here s.lock.Unlock() } - } } } diff --git a/pkg/network/server_test.go b/pkg/network/server_test.go index da1385430..d70618b54 100644 --- a/pkg/network/server_test.go +++ b/pkg/network/server_test.go @@ -178,7 +178,6 @@ func TestServerRegisterPeer(t *testing.T) { } return false }, time.Second, time.Millisecond*50) - } func TestGetBlocksByIndex(t *testing.T) { diff --git a/pkg/rpc/client/wsclient.go b/pkg/rpc/client/wsclient.go index 8a8e4824f..e0b9c7a52 100644 --- a/pkg/rpc/client/wsclient.go +++ b/pkg/rpc/client/wsclient.go @@ -209,7 +209,6 @@ func (c *WSClient) wsWriter() { } } } - } func (c *WSClient) makeWsRequest(r *request.Raw) (*response.Raw, error) { diff --git a/pkg/rpc/response/errors.go b/pkg/rpc/response/errors.go index 1e542dbd2..70201403b 100644 --- a/pkg/rpc/response/errors.go +++ b/pkg/rpc/response/errors.go @@ -44,7 +44,6 @@ func NewError(code int64, httpCode int, message string, data string, cause error Message: message, Data: data, } - } // NewParseError creates a new error with code diff --git a/pkg/rpc/server/server.go b/pkg/rpc/server/server.go index 085329474..5c06eb6b3 100644 --- a/pkg/rpc/server/server.go +++ b/pkg/rpc/server/server.go @@ -421,7 +421,6 @@ requestloop: break requestloop case resChan <- res: } - } s.subsLock.Lock() delete(s.subscribers, subscr) diff --git a/pkg/rpc/server/server_test.go b/pkg/rpc/server/server_test.go index 804426b34..d1d6138f8 100644 --- a/pkg/rpc/server/server_test.go +++ b/pkg/rpc/server/server_test.go @@ -1261,7 +1261,6 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] tc.check(t, e, res) } } - }) } }) diff --git a/pkg/rpc/server/subscription_test.go b/pkg/rpc/server/subscription_test.go index 9fe6ceafc..e2ca27ce4 100644 --- a/pkg/rpc/server/subscription_test.go +++ b/pkg/rpc/server/subscription_test.go @@ -311,7 +311,6 @@ func TestFilteredBlockSubscriptions(t *testing.T) { rmap := resp.Payload[0].(map[string]interface{}) primary := rmap["primary"].(float64) require.Equal(t, 3, int(primary)) - } callUnsubscribe(t, c, respMsgs, blockSubID) finishedFlag.CAS(false, true) diff --git a/pkg/services/oracle/neofs/neofs_test.go b/pkg/services/oracle/neofs/neofs_test.go index 6483875b9..82b25d4be 100644 --- a/pkg/services/oracle/neofs/neofs_test.go +++ b/pkg/services/oracle/neofs/neofs_test.go @@ -78,7 +78,6 @@ func TestParseNeoFSURL(t *testing.T) { require.Equal(t, tc.params, ps) } }) - } } diff --git a/pkg/services/oracle/transaction.go b/pkg/services/oracle/transaction.go index b76552f28..5902afe7c 100644 --- a/pkg/services/oracle/transaction.go +++ b/pkg/services/oracle/transaction.go @@ -79,7 +79,6 @@ func (t *incompleteTx) addResponse(pub *keys.PublicKey, sig []byte, isBackup boo ok: tx != nil, sig: sig, } - } // finalize checks is either main or backup tx has sufficient number of signatures and returns diff --git a/pkg/vm/vm_test.go b/pkg/vm/vm_test.go index d6d9a4e8a..2b3e97477 100644 --- a/pkg/vm/vm_test.go +++ b/pkg/vm/vm_test.go @@ -753,7 +753,6 @@ func TestArithNullArg(t *testing.T) { runWithArgs(t, prog, false, 0, stackitem.Null{}) runWithArgs(t, prog, nil, stackitem.NewInterop(nil), 1) // also has `.Value() == nil` }) - } } From 4e651eaf83265d433da632742be3ed0564043a83 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 22:52:07 +0300 Subject: [PATCH 29/34] compiler: simplify increments as suggested by golint --- pkg/compiler/native_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/compiler/native_test.go b/pkg/compiler/native_test.go index 08012b03f..12e5ab6d0 100644 --- a/pkg/compiler/native_test.go +++ b/pkg/compiler/native_test.go @@ -246,12 +246,12 @@ func getMethod(t *testing.T, ctr interop.ContractMD, name string, params []strin name = name[:4] case strings.HasPrefix(name, "memorySearch"): if strings.HasSuffix(name, "LastIndex") { - paramLen += 1 // true should be appended inside of an interop + paramLen++ // true should be appended inside of an interop } name = "memorySearch" case strings.HasPrefix(name, "stringSplit"): if strings.HasSuffix(name, "NonEmpty") { - paramLen += 1 // true should be appended inside of an interop + paramLen++ // true should be appended inside of an interop } name = "stringSplit" default: From d4a2f4d8b9e028686e934fb31f31e2e6cd1e61a0 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 22:52:32 +0300 Subject: [PATCH 30/34] hash: suppress staticcheck warning --- pkg/crypto/hash/hash.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/crypto/hash/hash.go b/pkg/crypto/hash/hash.go index 06ce1f421..45f18c7fd 100644 --- a/pkg/crypto/hash/hash.go +++ b/pkg/crypto/hash/hash.go @@ -5,7 +5,7 @@ import ( "encoding/binary" "github.com/nspcc-dev/neo-go/pkg/util" - "golang.org/x/crypto/ripemd160" + "golang.org/x/crypto/ripemd160" //nolint:staticcheck // SA1019: package golang.org/x/crypto/ripemd160 is deprecated ) // Hashable represents an object which can be hashed. Usually these objects From 3fdba9265fa8517538de77600bf7628255158788 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 22:53:28 +0300 Subject: [PATCH 31/34] add golangci-lint configuration It's mostly based on neofs-http-gate configuration, but has exhaustive disabled and some golint-specific warnings enabled (some of which are important for us). --- .golangci.yml | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 .golangci.yml diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..f4faf7672 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,58 @@ +# This file contains all available configuration options +# with their default values. + +# options for analysis running +run: + # timeout for analysis, e.g. 30s, 5m, default is 1m + timeout: 5m + + # include test files or not, default is true + tests: true + +# output configuration options +output: + # colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number" + format: tab + +# all available settings of specific linters +linters-settings: + exhaustive: + # indicates that switch statements are to be considered exhaustive if a + # 'default' case is present, even if all enum members aren't listed in the + # switch + default-signifies-exhaustive: true + govet: + # report about shadowed variables + check-shadowing: false + +linters: + enable: + # mandatory linters + - govet + - golint + + # some default golangci-lint linters + - deadcode + - errcheck + - gosimple + - ineffassign + - staticcheck + - structcheck + - typecheck + - unused + - varcheck + + # extra linters + # - exhaustive + - gofmt + - whitespace + - goimports + disable-all: true + fast: false + +issues: + include: + - EXC0002 # should have a comment + - EXC0003 # test/Test ... consider calling this + - EXC0004 # govet + - EXC0005 # C-style breaks From 9d2712573fa7573e9c54141d5a255e6bcd82348b Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 23:17:03 +0300 Subject: [PATCH 32/34] *: enable godot linter and fix all its warnings It's important for NeoGo to have clean documentation. No functional changes. --- .golangci.yml | 1 + cli/flags/address.go | 8 ++++---- cli/input/input.go | 2 +- cli/nep11_test.go | 2 +- cli/paramcontext/context.go | 2 +- cli/smartcontract/smart_contract.go | 2 +- pkg/compiler/codegen.go | 4 ++-- pkg/compiler/debug.go | 4 ++-- pkg/compiler/inline.go | 10 +++++----- pkg/consensus/commit.go | 2 +- pkg/consensus/payload.go | 2 +- pkg/core/block/block.go | 2 +- pkg/core/block/header.go | 4 ++-- pkg/core/dao/dao.go | 2 +- pkg/core/fee/calculate.go | 2 +- pkg/core/helper_test.go | 2 +- pkg/core/mempool/mem_pool.go | 6 +++--- pkg/core/mpt/batch_test.go | 2 +- pkg/core/native/ledger.go | 4 ++-- pkg/core/native/name_service_test.go | 2 +- pkg/core/native/oracle.go | 4 ++-- pkg/core/native/policy.go | 2 +- pkg/core/state/contract.go | 2 +- pkg/core/state/notification_event.go | 2 +- pkg/core/storage/badgerdb_store.go | 6 +++--- pkg/core/storage/store.go | 4 ++-- pkg/core/transaction/attrtype.go | 4 ++-- pkg/core/transaction/helper_test.go | 2 +- pkg/core/transaction/signer.go | 2 +- pkg/core/transaction/transaction.go | 8 ++++---- pkg/crypto/keys/publickey.go | 2 +- pkg/encoding/bigint/bigint.go | 2 +- pkg/encoding/bigint/bigint_test.go | 2 +- pkg/encoding/fixedn/fixed8.go | 2 +- pkg/interop/native/std/std.go | 10 +++++----- pkg/interop/types.go | 2 +- pkg/io/binaryReader.go | 2 +- pkg/network/capability/capability.go | 12 ++++++------ pkg/network/capability/type.go | 8 ++++---- pkg/network/discovery.go | 4 ++-- pkg/network/message.go | 16 ++++++++-------- pkg/network/payload/getblockbyindex.go | 4 ++-- pkg/network/payload/getblocks.go | 4 ++-- pkg/rpc/client/client.go | 6 +++--- pkg/rpc/client/rpc.go | 2 +- pkg/rpc/request/types.go | 2 +- pkg/rpc/response/errors.go | 18 +++++++++--------- pkg/rpc/response/result/unclaimed_gas.go | 4 ++-- pkg/rpc/rpc_config.go | 2 +- pkg/rpc/server/server.go | 2 +- pkg/smartcontract/convertor.go | 2 +- pkg/smartcontract/param_type.go | 2 +- pkg/smartcontract/trigger/trigger_type.go | 2 +- pkg/util/uint256.go | 2 +- pkg/vm/opcode/opcode.go | 20 ++++++++++---------- pkg/vm/stackitem/item.go | 4 ++-- pkg/vm/vm.go | 8 ++++---- pkg/vm/vm_test.go | 2 +- pkg/wallet/token.go | 2 +- pkg/wallet/wallet.go | 2 +- 60 files changed, 127 insertions(+), 126 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index f4faf7672..39a4d8e51 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -35,6 +35,7 @@ linters: - deadcode - errcheck - gosimple + - godot - ineffassign - staticcheck - structcheck diff --git a/cli/flags/address.go b/cli/flags/address.go index ce2276e63..56ccf851e 100644 --- a/cli/flags/address.go +++ b/cli/flags/address.go @@ -16,7 +16,7 @@ type Address struct { Value util.Uint160 } -// AddressFlag is a flag with type string +// AddressFlag is a flag with type string. type AddressFlag struct { Name string Usage string @@ -60,7 +60,7 @@ func (f AddressFlag) IsSet() bool { } // String returns a readable representation of this value -// (for usage defaults) +// (for usage defaults). func (f AddressFlag) String() string { var names []string eachName(f.Name, func(name string) { @@ -77,13 +77,13 @@ func getNameHelp(name string) string { return fmt.Sprintf("--%s value", name) } -// GetName returns the name of the flag +// GetName returns the name of the flag. func (f AddressFlag) GetName() string { return f.Name } // Apply populates the flag given the flag set and environment -// Ignores errors +// Ignores errors. func (f AddressFlag) Apply(set *flag.FlagSet) { eachName(f.Name, func(name string) { set.Var(&f.Value, name, f.Usage) diff --git a/cli/input/input.go b/cli/input/input.go index ee62a531a..22eb4a6c8 100644 --- a/cli/input/input.go +++ b/cli/input/input.go @@ -17,7 +17,7 @@ type ReadWriter struct { io.Writer } -// ReadLine reads line from the input without trailing '\n' +// ReadLine reads line from the input without trailing '\n'. func ReadLine(prompt string) (string, error) { trm := Terminal if trm == nil { diff --git a/cli/nep11_test.go b/cli/nep11_test.go index 3565b14b7..99fbeabbe 100644 --- a/cli/nep11_test.go +++ b/cli/nep11_test.go @@ -21,7 +21,7 @@ import ( ) const ( - // nftOwnerAddr is the owner of NFT-ND HASHY token (../examples/nft-nd/nft.go) + // nftOwnerAddr is the owner of NFT-ND HASHY token (../examples/nft-nd/nft.go). nftOwnerAddr = "NbrUYaZgyhSkNoRo9ugRyEMdUZxrhkNaWB" nftOwnerWallet = "../examples/my_wallet.json" nftOwnerPass = "qwerty" diff --git a/cli/paramcontext/context.go b/cli/paramcontext/context.go index 9df147fd0..c991e2e85 100644 --- a/cli/paramcontext/context.go +++ b/cli/paramcontext/context.go @@ -12,7 +12,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/wallet" ) -// validUntilBlockIncrement is the number of extra blocks to add to an exported transaction +// validUntilBlockIncrement is the number of extra blocks to add to an exported transaction. const validUntilBlockIncrement = 50 // InitAndSave creates incompletely signed transaction which can used diff --git a/cli/smartcontract/smart_contract.go b/cli/smartcontract/smart_contract.go index c3662696d..070a9ef7c 100644 --- a/cli/smartcontract/smart_contract.go +++ b/cli/smartcontract/smart_contract.go @@ -68,7 +68,7 @@ var ( const ( // smartContractTmpl is written to a file when used with `init` command. - // %s is parsed to be the smartContractName + // %s is parsed to be the smartContractName. smartContractTmpl = `package %s import "github.com/nspcc-dev/neo-go/pkg/interop/runtime" diff --git a/pkg/compiler/codegen.go b/pkg/compiler/codegen.go index 14a456165..2723f861b 100644 --- a/pkg/compiler/codegen.go +++ b/pkg/compiler/codegen.go @@ -126,7 +126,7 @@ const ( varArgument ) -// newLabel creates a new label to jump to +// newLabel creates a new label to jump to. func (c *codegen) newLabel() (l uint16) { li := len(c.l) if li > math.MaxUint16 { @@ -1498,7 +1498,7 @@ func (c *codegen) getLabelOffset(typ labelOffsetType, name string) uint16 { } // For `&&` and `||` it return an opcode which jumps only if result is known: -// false && .. == false, true || .. = true +// false && .. == false, true || .. = true. func getJumpForToken(tok token.Token, typ types.Type) (opcode.Opcode, bool) { switch tok { case token.GTR: diff --git a/pkg/compiler/debug.go b/pkg/compiler/debug.go index 042d47fd5..9ec74af29 100644 --- a/pkg/compiler/debug.go +++ b/pkg/compiler/debug.go @@ -340,7 +340,7 @@ func (d *DebugParam) UnmarshalJSON(data []byte) error { return nil } -// ToManifestParameter converts DebugParam to manifest.Parameter +// ToManifestParameter converts DebugParam to manifest.Parameter. func (d *DebugParam) ToManifestParameter() manifest.Parameter { return manifest.Parameter{ Name: d.Name, @@ -348,7 +348,7 @@ func (d *DebugParam) ToManifestParameter() manifest.Parameter { } } -// ToManifestMethod converts MethodDebugInfo to manifest.Method +// ToManifestMethod converts MethodDebugInfo to manifest.Method. func (m *MethodDebugInfo) ToManifestMethod() manifest.Method { var ( result manifest.Method diff --git a/pkg/compiler/inline.go b/pkg/compiler/inline.go index 4da30043d..f3471863b 100644 --- a/pkg/compiler/inline.go +++ b/pkg/compiler/inline.go @@ -10,11 +10,11 @@ import ( // inlineCall inlines call of n for function represented by f. // Call `f(a,b)` for definition `func f(x,y int)` is translated to block: -// { -// x := a -// y := b -// -// } +// { +// x := a +// y := b +// +// } func (c *codegen) inlineCall(f *funcScope, n *ast.CallExpr) { labelSz := len(c.labelList) offSz := len(c.inlineLabelOffsets) diff --git a/pkg/consensus/commit.go b/pkg/consensus/commit.go index 492a1a156..920d67745 100644 --- a/pkg/consensus/commit.go +++ b/pkg/consensus/commit.go @@ -11,7 +11,7 @@ type commit struct { } // signatureSize is an rfc6989 signature size in bytes -// without leading byte (0x04, uncompressed) +// without leading byte (0x04, uncompressed). const signatureSize = 64 var _ payload.Commit = (*commit)(nil) diff --git a/pkg/consensus/payload.go b/pkg/consensus/payload.go index 2d17938ea..e4ae53066 100644 --- a/pkg/consensus/payload.go +++ b/pkg/consensus/payload.go @@ -233,7 +233,7 @@ func (p *Payload) encodeData() { } } -// decode data of payload into it's message +// decode data of payload into its message. func (p *Payload) decodeData() error { br := io.NewBinReaderFromBuf(p.Extensible.Data) p.message.DecodeBinary(br) diff --git a/pkg/core/block/block.go b/pkg/core/block/block.go index 8feff8942..37d705ef5 100644 --- a/pkg/core/block/block.go +++ b/pkg/core/block/block.go @@ -215,7 +215,7 @@ func (b *Block) UnmarshalJSON(data []byte) error { return nil } -// GetExpectedBlockSize returns expected block size which should be equal to io.GetVarSize(b) +// GetExpectedBlockSize returns expected block size which should be equal to io.GetVarSize(b). func (b *Block) GetExpectedBlockSize() int { var transactionsSize int for _, tx := range b.Transactions { diff --git a/pkg/core/block/header.go b/pkg/core/block/header.go index e7515dcab..c4025428d 100644 --- a/pkg/core/block/header.go +++ b/pkg/core/block/header.go @@ -11,7 +11,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// Header holds the base info of a block +// Header holds the base info of a block. type Header struct { // Version of the block. Version uint32 @@ -84,7 +84,7 @@ func (b *Header) DecodeBinary(br *io.BinReader) { b.Script.DecodeBinary(br) } -// EncodeBinary implements Serializable interface +// EncodeBinary implements Serializable interface. func (b *Header) EncodeBinary(bw *io.BinWriter) { b.encodeHashableFields(bw) bw.WriteVarUint(1) diff --git a/pkg/core/dao/dao.go b/pkg/core/dao/dao.go index 9e1f371f7..12e4ecfe7 100644 --- a/pkg/core/dao/dao.go +++ b/pkg/core/dao/dao.go @@ -17,7 +17,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// HasTransaction errors +// HasTransaction errors. var ( // ErrAlreadyExists is returned when transaction exists in dao. ErrAlreadyExists = errors.New("transaction already exists") diff --git a/pkg/core/fee/calculate.go b/pkg/core/fee/calculate.go index c15874932..4942f3f89 100644 --- a/pkg/core/fee/calculate.go +++ b/pkg/core/fee/calculate.go @@ -10,7 +10,7 @@ import ( // ECDSAVerifyPrice is a gas price of a single verification. const ECDSAVerifyPrice = 1 << 15 -// Calculate returns network fee for transaction +// Calculate returns network fee for transaction. func Calculate(base int64, script []byte) (int64, int) { var ( netFee int64 diff --git a/pkg/core/helper_test.go b/pkg/core/helper_test.go index 32a470175..24c8cafd1 100644 --- a/pkg/core/helper_test.go +++ b/pkg/core/helper_test.go @@ -44,7 +44,7 @@ import ( "go.uber.org/zap/zaptest" ) -// multisig address which possess all NEO +// multisig address which possess all NEO. var neoOwner = testchain.MultisigScriptHash() // newTestChain should be called before newBlock invocation to properly setup diff --git a/pkg/core/mempool/mem_pool.go b/pkg/core/mempool/mem_pool.go index 1215b9f52..53b6f60bb 100644 --- a/pkg/core/mempool/mem_pool.go +++ b/pkg/core/mempool/mem_pool.go @@ -47,7 +47,7 @@ type item struct { type items []item // utilityBalanceAndFees stores sender's balance and overall fees of -// sender's transactions which are currently in mempool +// sender's transactions which are currently in mempool. type utilityBalanceAndFees struct { balance *big.Int feeSum *big.Int @@ -158,7 +158,7 @@ func (mp *Pool) HasConflicts(t *transaction.Transaction, fee Feer) bool { } // tryAddSendersFee tries to add system fee and network fee to the total sender`s fee in mempool -// and returns false if both balance check is required and sender has not enough GAS to pay +// and returns false if both balance check is required and sender has not enough GAS to pay. func (mp *Pool) tryAddSendersFee(tx *transaction.Transaction, feer Feer, needCheck bool) bool { payer := tx.Signers[mp.payerIndex].Account senderFee, ok := mp.fees[payer] @@ -304,7 +304,7 @@ func (mp *Pool) Remove(hash util.Uint256, feer Feer) { mp.lock.Unlock() } -// removeInternal is an internal unlocked representation of Remove +// removeInternal is an internal unlocked representation of Remove. func (mp *Pool) removeInternal(hash util.Uint256, feer Feer) { if tx, ok := mp.verifiedMap[hash]; ok { var num int diff --git a/pkg/core/mpt/batch_test.go b/pkg/core/mpt/batch_test.go index dffb4b9ae..9438b8e2b 100644 --- a/pkg/core/mpt/batch_test.go +++ b/pkg/core/mpt/batch_test.go @@ -281,7 +281,7 @@ var _ = printNode // This function is unused, but is helpful for debugging // as it provides more readable Trie representation compared to -// `spew.Dump()` +// `spew.Dump()`. func printNode(prefix string, n Node) { switch tn := n.(type) { case *HashNode: diff --git a/pkg/core/native/ledger.go b/pkg/core/native/ledger.go index 4dfd6b313..ad9b68185 100644 --- a/pkg/core/native/ledger.go +++ b/pkg/core/native/ledger.go @@ -192,7 +192,7 @@ func getTransactionAndHeight(cd *dao.Cached, item stackitem.Item) (*transaction. return cd.GetTransaction(hash) } -// BlockToStackItem converts block.Block to stackitem.Item +// BlockToStackItem converts block.Block to stackitem.Item. func BlockToStackItem(b *block.Block) stackitem.Item { return stackitem.NewArray([]stackitem.Item{ stackitem.NewByteArray(b.Hash().BytesBE()), @@ -206,7 +206,7 @@ func BlockToStackItem(b *block.Block) stackitem.Item { }) } -// TransactionToStackItem converts transaction.Transaction to stackitem.Item +// TransactionToStackItem converts transaction.Transaction to stackitem.Item. func TransactionToStackItem(t *transaction.Transaction) stackitem.Item { return stackitem.NewArray([]stackitem.Item{ stackitem.NewByteArray(t.Hash().BytesBE()), diff --git a/pkg/core/native/name_service_test.go b/pkg/core/native/name_service_test.go index bc741051f..325ffd831 100644 --- a/pkg/core/native/name_service_test.go +++ b/pkg/core/native/name_service_test.go @@ -10,7 +10,7 @@ import ( ) // The specification is following C# code: -// string domain = string.Join('.', name.Split('.')[^2..]); +// string domain = string.Join('.', name.Split('.')[^2..]); func TestParseDomain(t *testing.T) { testCases := []struct { name string diff --git a/pkg/core/native/oracle.go b/pkg/core/native/oracle.go index abd99fbf5..b6deb469c 100644 --- a/pkg/core/native/oracle.go +++ b/pkg/core/native/oracle.go @@ -56,7 +56,7 @@ const ( maxFilterLength = 128 maxCallbackLength = 32 maxUserDataLength = 512 - // maxRequestsCount is the maximum number of requests per URL + // maxRequestsCount is the maximum number of requests per URL. maxRequestsCount = 256 // DefaultOracleRequestPrice is default amount GAS needed for oracle request. @@ -520,7 +520,7 @@ func (o *Oracle) getSerializableFromDAO(d dao.DAO, key []byte, item io.Serializa return getSerializableFromDAO(o.ID, d, key, item) } -// updateCache updates cached Oracle values if they've been changed +// updateCache updates cached Oracle values if they've been changed. func (o *Oracle) updateCache(d dao.DAO) error { orc, _ := o.Module.Load().(services.Oracle) if orc == nil { diff --git a/pkg/core/native/policy.go b/pkg/core/native/policy.go index 8c063bca7..78f346605 100644 --- a/pkg/core/native/policy.go +++ b/pkg/core/native/policy.go @@ -243,7 +243,7 @@ func (p *Policy) isBlocked(ic *interop.Context, args []stackitem.Item) stackitem return stackitem.NewBool(p.IsBlockedInternal(ic.DAO, hash)) } -// IsBlockedInternal checks whether provided account is blocked +// IsBlockedInternal checks whether provided account is blocked. func (p *Policy) IsBlockedInternal(dao dao.DAO, hash util.Uint160) bool { p.lock.RLock() defer p.lock.RUnlock() diff --git a/pkg/core/state/contract.go b/pkg/core/state/contract.go index 6c2fd0310..3c6da196b 100644 --- a/pkg/core/state/contract.go +++ b/pkg/core/state/contract.go @@ -54,7 +54,7 @@ func (c *Contract) EncodeBinary(w *io.BinWriter) { stackitem.EncodeBinaryStackItem(si, w) } -// ToStackItem converts state.Contract to stackitem.Item +// ToStackItem converts state.Contract to stackitem.Item. func (c *Contract) ToStackItem() (stackitem.Item, error) { rawNef, err := c.NEF.Bytes() if err != nil { diff --git a/pkg/core/state/notification_event.go b/pkg/core/state/notification_event.go index d7b2706e8..a7c032b76 100644 --- a/pkg/core/state/notification_event.go +++ b/pkg/core/state/notification_event.go @@ -129,7 +129,7 @@ func (ne *NotificationEvent) UnmarshalJSON(data []byte) error { return nil } -// appExecResultAux is an auxiliary struct for JSON marshalling +// appExecResultAux is an auxiliary struct for JSON marshalling. type appExecResultAux struct { Container util.Uint256 `json:"container"` } diff --git a/pkg/core/storage/badgerdb_store.go b/pkg/core/storage/badgerdb_store.go index 277487058..619ca592a 100644 --- a/pkg/core/storage/badgerdb_store.go +++ b/pkg/core/storage/badgerdb_store.go @@ -17,12 +17,12 @@ type BadgerDBStore struct { db *badger.DB } -// BadgerDBBatch is a wrapper around badger.WriteBatch, compatible with Batch interface +// BadgerDBBatch is a wrapper around badger.WriteBatch, compatible with Batch interface. type BadgerDBBatch struct { batch *badger.WriteBatch } -// Delete implements the Batch interface +// Delete implements the Batch interface. func (b *BadgerDBBatch) Delete(key []byte) { err := b.batch.Delete(key) if err != nil { @@ -30,7 +30,7 @@ func (b *BadgerDBBatch) Delete(key []byte) { } } -// Put implements the Batch interface +// Put implements the Batch interface. func (b *BadgerDBBatch) Put(key, value []byte) { keycopy := make([]byte, len(key)) copy(keycopy, key) diff --git a/pkg/core/storage/store.go b/pkg/core/storage/store.go index 14bd13888..fe2d15703 100644 --- a/pkg/core/storage/store.go +++ b/pkg/core/storage/store.go @@ -69,7 +69,7 @@ func (k KeyPrefix) Bytes() []byte { } // AppendPrefix appends byteslice b to the given KeyPrefix. -// AppendKeyPrefix(SYSVersion, []byte{0x00, 0x01}) +// AppendKeyPrefix(SYSVersion, []byte{0x00, 0x01}). func AppendPrefix(k KeyPrefix, b []byte) []byte { dest := make([]byte, len(b)+1) dest[0] = byte(k) @@ -78,7 +78,7 @@ func AppendPrefix(k KeyPrefix, b []byte) []byte { } // AppendPrefixInt append int n to the given KeyPrefix. -//AppendPrefixInt(SYSCurrentHeader, 10001) +// AppendPrefixInt(SYSCurrentHeader, 10001) func AppendPrefixInt(k KeyPrefix, n int) []byte { b := make([]byte, 4) binary.LittleEndian.PutUint32(b, uint32(n)) diff --git a/pkg/core/transaction/attrtype.go b/pkg/core/transaction/attrtype.go index c6879fefa..7f339245f 100644 --- a/pkg/core/transaction/attrtype.go +++ b/pkg/core/transaction/attrtype.go @@ -6,9 +6,9 @@ package transaction type AttrType uint8 const ( - // ReservedLowerBound is the lower bound of reserved attribute types + // ReservedLowerBound is the lower bound of reserved attribute types. ReservedLowerBound = 0xe0 - // ReservedUpperBound is the upper bound of reserved attribute types + // ReservedUpperBound is the upper bound of reserved attribute types. ReservedUpperBound = 0xff ) diff --git a/pkg/core/transaction/helper_test.go b/pkg/core/transaction/helper_test.go index 13987a18c..53f53e079 100644 --- a/pkg/core/transaction/helper_test.go +++ b/pkg/core/transaction/helper_test.go @@ -8,7 +8,7 @@ import ( ) var ( - // tx from C# privnet 0x25426643feed564cd3e57f346d6c68692f5622b3063da11c5572d99ee1a5b49a + // tx from C# privnet 0x25426643feed564cd3e57f346d6c68692f5622b3063da11c5572d99ee1a5b49a. rawInvocationTX = "ANgkvBnA2KcAAAAAACCqRAAAAAAA6AMAAAHe7nnBifMAmLC6ai65CzqSWKbH/wEAXwsDAEDZ3YhNCgAMFIDOx7b1tW9QV49zfxYtOrFNRmUNDBTe7nnBifMAmLC6ai65CzqSWKbH/xTAHwwIdHJhbnNmZXIMFM924ovQBixKR47jVWEBExnzz6TSQWJ9W1I5AcYMQNafQPvPYQuqk3yCFwz8+18XCjnr8F8Rqx8e5IoQIkxjG9TjuvZm1KKGDn2UbFJnMey/FPLqezK8nbbJw2Eg10kMQKXrVyD3fs38e6Mqwsy7bAkxLsLnhvMnerbYLOqWW/DdinzT1RKAoOz5b7dAPusj5IWzQ6EifSCigJRTp//XdaMMQOv1d15PkIZM7wIvQmKDNxNy5yzQYFyoezx9Og7rM+64J9LtaHp3LFIKKNPgDhL7sFR1bd2w7vzbyR7V+Pyg3GaTEwwhAhA6f33QFlWFl/eWDSfFFqQ5T9loueZRVetLAT5AQEBuDCECp7xV/oaE4BGXaNEEujB5W9zIZhnoZK3SYVZyPtGFzWIMIQKzYiv0AXvf4xfFiu1fTHU/IGt9uJYEb6fXdLvEv3+NwgwhA9kMB99j5pDOd5EuEKtRrMlEtmhgI3tgjE+PgwnnHuaZFEF7zmyl" ) diff --git a/pkg/core/transaction/signer.go b/pkg/core/transaction/signer.go index 7cb93940e..ef409e25b 100644 --- a/pkg/core/transaction/signer.go +++ b/pkg/core/transaction/signer.go @@ -8,7 +8,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// The maximum number of AllowedContracts or AllowedGroups +// The maximum number of AllowedContracts or AllowedGroups. const maxSubitems = 16 // Signer implements a Transaction signer. diff --git a/pkg/core/transaction/transaction.go b/pkg/core/transaction/transaction.go index d49b8061d..893c72024 100644 --- a/pkg/core/transaction/transaction.go +++ b/pkg/core/transaction/transaction.go @@ -230,7 +230,7 @@ func (t *Transaction) DecodeHashableFields(buf []byte) error { return nil } -// Bytes converts the transaction to []byte +// Bytes converts the transaction to []byte. func (t *Transaction) Bytes() []byte { buf := io.NewBufBinWriter() t.EncodeBinary(buf.BinWriter) @@ -240,7 +240,7 @@ func (t *Transaction) Bytes() []byte { return buf.Bytes() } -// NewTransactionFromBytes decodes byte array into *Transaction +// NewTransactionFromBytes decodes byte array into *Transaction. func NewTransactionFromBytes(b []byte) (*Transaction, error) { tx := &Transaction{} r := io.NewBinReaderFromBuf(b) @@ -257,7 +257,7 @@ func NewTransactionFromBytes(b []byte) (*Transaction, error) { } // FeePerByte returns NetworkFee of the transaction divided by -// its size +// its size. func (t *Transaction) FeePerByte() int64 { return t.NetworkFee / int64(t.Size()) } @@ -280,7 +280,7 @@ func (t *Transaction) Sender() util.Uint160 { } // transactionJSON is a wrapper for Transaction and -// used for correct marhalling of transaction.Data +// used for correct marhalling of transaction.Data. type transactionJSON struct { TxID util.Uint256 `json:"hash"` Size int `json:"size"` diff --git a/pkg/crypto/keys/publickey.go b/pkg/crypto/keys/publickey.go index a3660d616..b7954bdd1 100644 --- a/pkg/crypto/keys/publickey.go +++ b/pkg/crypto/keys/publickey.go @@ -203,7 +203,7 @@ func NewPublicKeyFromASN1(data []byte) (*PublicKey, error) { // 1. Secp256k1 (Koblitz curve): y² = x³ + b, // 2. Secp256r1 (Random curve): y² = x³ - 3x + b. // To decode compressed curve point we perform the following operation: y = sqrt(x³ + ax + b mod p) -// where `p` denotes the order of the underlying curve field +// where `p` denotes the order of the underlying curve field. func decodeCompressedY(x *big.Int, ylsb uint, curve elliptic.Curve) (*big.Int, error) { var a *big.Int switch curve.(type) { diff --git a/pkg/encoding/bigint/bigint.go b/pkg/encoding/bigint/bigint.go index ed562821d..15d6df77b 100644 --- a/pkg/encoding/bigint/bigint.go +++ b/pkg/encoding/bigint/bigint.go @@ -9,7 +9,7 @@ import ( const ( // MaxBytesLen is the maximum length of serialized integer suitable for Neo VM. MaxBytesLen = 33 // 32 bytes for 256-bit integer plus 1 if padding needed - // wordSizeBytes is a size of a big.Word (uint) in bytes.` + // wordSizeBytes is a size of a big.Word (uint) in bytes. wordSizeBytes = bits.UintSize / 8 ) diff --git a/pkg/encoding/bigint/bigint_test.go b/pkg/encoding/bigint/bigint_test.go index 7b0455c34..bb8c2207c 100644 --- a/pkg/encoding/bigint/bigint_test.go +++ b/pkg/encoding/bigint/bigint_test.go @@ -149,7 +149,7 @@ var stringCases = []struct { // this cases are from stdlib // https://github.com/dotnet/runtime/blob/master/src/libraries/System.Runtime.Numerics/tests/BigInteger/ToByteArray.cs#L96 -// note that they are in big-endian +// note that they are in big-endian. var stdlibCases = []struct { numStr string buf []byte diff --git a/pkg/encoding/fixedn/fixed8.go b/pkg/encoding/fixedn/fixed8.go index 01abc8720..af3b82f9c 100644 --- a/pkg/encoding/fixedn/fixed8.go +++ b/pkg/encoding/fixedn/fixed8.go @@ -65,7 +65,7 @@ func Fixed8FromFloat(val float64) Fixed8 { } // Fixed8FromString parses s which must be a fixed point number -// with precision up to 10^-8 +// with precision up to 10^-8. func Fixed8FromString(s string) (Fixed8, error) { num, err := FromString(s, precision) if err != nil { diff --git a/pkg/interop/native/std/std.go b/pkg/interop/native/std/std.go index af263c8ba..135de27eb 100644 --- a/pkg/interop/native/std/std.go +++ b/pkg/interop/native/std/std.go @@ -46,11 +46,11 @@ func JSONSerialize(item interface{}) []byte { // JSONDeserialize deserializes value from json. It uses `jsonDeserialize` method of StdLib // native contract. // It performs deserialization as follows: -// strings -> []byte (string) from base64 -// integers -> (u)int* types -// null -> interface{}(nil) -// arrays -> []interface{} -// maps -> map[string]interface{} +// strings -> []byte (string) from base64 +// integers -> (u)int* types +// null -> interface{}(nil) +// arrays -> []interface{} +// maps -> map[string]interface{} func JSONDeserialize(data []byte) interface{} { return contract.Call(interop.Hash160(Hash), "jsonDeserialize", contract.NoneFlag, data) diff --git a/pkg/interop/types.go b/pkg/interop/types.go index f6ae0b11e..5ed473ccc 100644 --- a/pkg/interop/types.go +++ b/pkg/interop/types.go @@ -13,5 +13,5 @@ type Hash256 []byte type PublicKey []byte // Interface represents interop interface type which is needed for -// transparent handling of VM-internal types (e.g. storage.Context) +// transparent handling of VM-internal types (e.g. storage.Context). type Interface interface{} diff --git a/pkg/io/binaryReader.go b/pkg/io/binaryReader.go index 6915f5109..fdcb08249 100644 --- a/pkg/io/binaryReader.go +++ b/pkg/io/binaryReader.go @@ -167,7 +167,7 @@ func (r *BinReader) ReadVarUint() uint64 { } // ReadVarBytes reads the next set of bytes from the underlying reader. -// ReadVarUInt() is used to determine how large that slice is +// ReadVarUInt() is used to determine how large that slice is. func (r *BinReader) ReadVarBytes(maxSize ...int) []byte { n := r.ReadVarUint() ms := MaxArraySize diff --git a/pkg/network/capability/capability.go b/pkg/network/capability/capability.go index 7b489ef3a..32073129f 100644 --- a/pkg/network/capability/capability.go +++ b/pkg/network/capability/capability.go @@ -6,10 +6,10 @@ import ( "github.com/nspcc-dev/neo-go/pkg/io" ) -// MaxCapabilities is the maximum number of capabilities per payload +// MaxCapabilities is the maximum number of capabilities per payload. const MaxCapabilities = 32 -// Capabilities is a list of Capability +// Capabilities is a list of Capability. type Capabilities []Capability // DecodeBinary implements Serializable interface. @@ -49,7 +49,7 @@ func (cs Capabilities) checkUniqueCapabilities() error { return nil } -// Capability describes network service available for node +// Capability describes network service available for node. type Capability struct { Type Type Data io.Serializable @@ -80,7 +80,7 @@ func (c *Capability) EncodeBinary(bw *io.BinWriter) { c.Data.EncodeBinary(bw) } -// Node represents full node capability with start height +// Node represents full node capability with start height. type Node struct { StartHeight uint32 } @@ -95,9 +95,9 @@ func (n *Node) EncodeBinary(bw *io.BinWriter) { bw.WriteU32LE(n.StartHeight) } -// Server represents TCP or WS server capability with port +// Server represents TCP or WS server capability with port. type Server struct { - // Port is the port this server is listening on + // Port is the port this server is listening on. Port uint16 } diff --git a/pkg/network/capability/type.go b/pkg/network/capability/type.go index b25b15397..0955c1b38 100644 --- a/pkg/network/capability/type.go +++ b/pkg/network/capability/type.go @@ -1,13 +1,13 @@ package capability -// Type represents node capability type +// Type represents node capability type. type Type byte const ( - // TCPServer represents TCP node capability type + // TCPServer represents TCP node capability type. TCPServer Type = 0x01 - // WSServer represents WebSocket node capability type + // WSServer represents WebSocket node capability type. WSServer Type = 0x02 - // FullNode represents full node capability type + // FullNode represents full node capability type. FullNode Type = 0x10 ) diff --git a/pkg/network/discovery.go b/pkg/network/discovery.go index 25da5a5ba..1a56b703f 100644 --- a/pkg/network/discovery.go +++ b/pkg/network/discovery.go @@ -28,7 +28,7 @@ type Discoverer interface { GoodPeers() []AddressWithCapabilities } -// AddressWithCapabilities represents node address with its capabilities +// AddressWithCapabilities represents node address with its capabilities. type AddressWithCapabilities struct { Address string Capabilities capability.Capabilities @@ -94,7 +94,7 @@ func (d *DefaultDiscovery) PoolCount() int { } // pushToPoolOrDrop tries to push address given into the pool, but if the pool -// is already full, it just drops it +// is already full, it just drops it. func (d *DefaultDiscovery) pushToPoolOrDrop(addr string) { select { case d.pool <- addr: diff --git a/pkg/network/message.go b/pkg/network/message.go index 1a8025cb0..f2892aae9 100644 --- a/pkg/network/message.go +++ b/pkg/network/message.go @@ -34,10 +34,10 @@ type Message struct { StateRootInHeader bool } -// MessageFlag represents compression level of message payload +// MessageFlag represents compression level of message payload. type MessageFlag byte -// Possible message flags +// Possible message flags. const ( Compressed MessageFlag = 1 << iota None MessageFlag = 0 @@ -48,17 +48,17 @@ type CommandType byte // Valid protocol commands used to send between nodes. const ( - // handshaking + // Handshaking. CMDVersion CommandType = 0x00 CMDVerack CommandType = 0x01 - // connectivity + // Connectivity. CMDGetAddr CommandType = 0x10 CMDAddr CommandType = 0x11 CMDPing CommandType = 0x18 CMDPong CommandType = 0x19 - // synchronization + // Synchronization. CMDGetHeaders CommandType = 0x20 CMDHeaders CommandType = 0x21 CMDGetBlocks CommandType = 0x24 @@ -73,13 +73,13 @@ const ( CMDP2PNotaryRequest = CommandType(payload.P2PNotaryRequestType) CMDReject CommandType = 0x2f - // SPV protocol + // SPV protocol. CMDFilterLoad CommandType = 0x30 CMDFilterAdd CommandType = 0x31 CMDFilterClear CommandType = 0x32 CMDMerkleBlock CommandType = 0x38 - // others + // Others. CMDAlert CommandType = 0x40 ) @@ -197,7 +197,7 @@ func (m *Message) Bytes() ([]byte, error) { } // tryCompressPayload sets message's compressed payload to serialized -// payload and compresses it in case if its size exceeds CompressionMinSize +// payload and compresses it in case if its size exceeds CompressionMinSize. func (m *Message) tryCompressPayload() error { if m.Payload == nil { return nil diff --git a/pkg/network/payload/getblockbyindex.go b/pkg/network/payload/getblockbyindex.go index a4e59db1d..372af4d08 100644 --- a/pkg/network/payload/getblockbyindex.go +++ b/pkg/network/payload/getblockbyindex.go @@ -6,13 +6,13 @@ import ( "github.com/nspcc-dev/neo-go/pkg/io" ) -// GetBlockByIndex payload +// GetBlockByIndex payload. type GetBlockByIndex struct { IndexStart uint32 Count int16 } -// NewGetBlockByIndex returns GetBlockByIndex payload with specified start index and count +// NewGetBlockByIndex returns GetBlockByIndex payload with specified start index and count. func NewGetBlockByIndex(indexStart uint32, count int16) *GetBlockByIndex { return &GetBlockByIndex{ IndexStart: indexStart, diff --git a/pkg/network/payload/getblocks.go b/pkg/network/payload/getblocks.go index e3434ebce..b881559a3 100644 --- a/pkg/network/payload/getblocks.go +++ b/pkg/network/payload/getblocks.go @@ -12,9 +12,9 @@ const ( MaxHashesCount = 500 ) -// GetBlocks contains fields and methods to be shared with the +// GetBlocks contains getblocks message payload fields. type GetBlocks struct { - // hash of latest block that node requests + // Hash of the latest block that node requests. HashStart util.Uint256 Count int16 } diff --git a/pkg/rpc/client/client.go b/pkg/rpc/client/client.go index 4623a9070..9011e680c 100644 --- a/pkg/rpc/client/client.go +++ b/pkg/rpc/client/client.go @@ -21,7 +21,7 @@ import ( const ( defaultDialTimeout = 4 * time.Second defaultRequestTimeout = 4 * time.Second - // number of blocks after which cache is expired + // Number of blocks after which cache is expired. cacheTimeout = 100 ) @@ -52,14 +52,14 @@ type Options struct { RequestTimeout time.Duration } -// cache stores cache values for the RPC client methods +// cache stores cache values for the RPC client methods. type cache struct { calculateValidUntilBlock calculateValidUntilBlockCache nativeHashes map[string]util.Uint160 } // calculateValidUntilBlockCache stores cached number of validators and -// cache expiration value in blocks +// cache expiration value in blocks. type calculateValidUntilBlockCache struct { validatorsCount uint32 expiresAt uint32 diff --git a/pkg/rpc/client/rpc.go b/pkg/rpc/client/rpc.go index db88ff0df..e51078fbf 100644 --- a/pkg/rpc/client/rpc.go +++ b/pkg/rpc/client/rpc.go @@ -463,7 +463,7 @@ func (c *Client) InvokeContractVerify(contract util.Uint160, params []smartcontr return c.invokeSomething("invokecontractverify", p, signers, witnesses...) } -// invokeSomething is an inner wrapper for Invoke* functions +// invokeSomething is an inner wrapper for Invoke* functions. func (c *Client) invokeSomething(method string, p request.RawParams, signers []transaction.Signer, witnesses ...transaction.Witness) (*result.Invoke, error) { var resp = new(result.Invoke) if signers != nil { diff --git a/pkg/rpc/request/types.go b/pkg/rpc/request/types.go index 8da4f31b5..450815489 100644 --- a/pkg/rpc/request/types.go +++ b/pkg/rpc/request/types.go @@ -61,7 +61,7 @@ type In struct { // batch: https://www.jsonrpc.org/specification#batch. type Batch []In -// MarshalJSON implements json.Marshaler interface +// MarshalJSON implements json.Marshaler interface. func (r Request) MarshalJSON() ([]byte, error) { if r.In != nil { return json.Marshal(r.In) diff --git a/pkg/rpc/response/errors.go b/pkg/rpc/response/errors.go index 70201403b..e19df1166 100644 --- a/pkg/rpc/response/errors.go +++ b/pkg/rpc/response/errors.go @@ -20,17 +20,17 @@ type ( var ( // ErrInvalidParams represents a generic 'invalid parameters' error. ErrInvalidParams = NewInvalidParamsError("", nil) - // ErrAlreadyExists represents SubmitError with code -501 + // ErrAlreadyExists represents SubmitError with code -501. ErrAlreadyExists = NewSubmitError(-501, "Block or transaction already exists and cannot be sent repeatedly.") - // ErrOutOfMemory represents SubmitError with code -502 + // ErrOutOfMemory represents SubmitError with code -502. ErrOutOfMemory = NewSubmitError(-502, "The memory pool is full and no more transactions can be sent.") - // ErrUnableToVerify represents SubmitError with code -503 + // ErrUnableToVerify represents SubmitError with code -503. ErrUnableToVerify = NewSubmitError(-503, "The block cannot be validated.") - // ErrValidationFailed represents SubmitError with code -504 + // ErrValidationFailed represents SubmitError with code -504. ErrValidationFailed = NewSubmitError(-504, "Block or transaction validation failed.") - // ErrPolicyFail represents SubmitError with code -505 + // ErrPolicyFail represents SubmitError with code -505. ErrPolicyFail = NewSubmitError(-505, "One of the Policy filters failed.") - // ErrUnknown represents SubmitError with code -500 + // ErrUnknown represents SubmitError with code -500. ErrUnknown = NewSubmitError(-500, "Unknown error.") ) @@ -47,7 +47,7 @@ func NewError(code int64, httpCode int, message string, data string, cause error } // NewParseError creates a new error with code -// -32700.:%s +// -32700. func NewParseError(data string, cause error) *Error { return NewError(-32700, http.StatusBadRequest, "Parse Error", data, cause) } @@ -77,13 +77,13 @@ func NewInternalServerError(data string, cause error) *Error { } // NewRPCError creates a new error with -// code -100 +// code -100. func NewRPCError(message string, data string, cause error) *Error { return NewError(-100, http.StatusUnprocessableEntity, message, data, cause) } // NewSubmitError creates a new error with -// specified error code and error message +// specified error code and error message. func NewSubmitError(code int64, message string) *Error { return NewError(code, http.StatusUnprocessableEntity, message, "", nil) } diff --git a/pkg/rpc/response/result/unclaimed_gas.go b/pkg/rpc/response/result/unclaimed_gas.go index af051acdd..ae62b4124 100644 --- a/pkg/rpc/response/result/unclaimed_gas.go +++ b/pkg/rpc/response/result/unclaimed_gas.go @@ -9,13 +9,13 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// UnclaimedGas response wrapper +// UnclaimedGas response wrapper. type UnclaimedGas struct { Address util.Uint160 Unclaimed big.Int } -// unclaimedGas is an auxiliary struct for JSON marhsalling +// unclaimedGas is an auxiliary struct for JSON marhsalling. type unclaimedGas struct { Address string `json:"address"` Unclaimed string `json:"unclaimed"` diff --git a/pkg/rpc/rpc_config.go b/pkg/rpc/rpc_config.go index 27bd8bb4b..17aedec0c 100644 --- a/pkg/rpc/rpc_config.go +++ b/pkg/rpc/rpc_config.go @@ -5,7 +5,7 @@ import ( ) type ( - // Config is an RPC service configuration information + // Config is an RPC service configuration information. Config struct { Address string `yaml:"Address"` Enabled bool `yaml:"Enabled"` diff --git a/pkg/rpc/server/server.go b/pkg/rpc/server/server.go index 5c06eb6b3..3a62b3e6d 100644 --- a/pkg/rpc/server/server.go +++ b/pkg/rpc/server/server.go @@ -1179,7 +1179,7 @@ func (s *Server) getNextBlockValidators(_ request.Params) (interface{}, *respons return res, nil } -// getCommittee returns the current list of NEO committee members +// getCommittee returns the current list of NEO committee members. func (s *Server) getCommittee(_ request.Params) (interface{}, *response.Error) { keys, err := s.chain.GetCommittee() if err != nil { diff --git a/pkg/smartcontract/convertor.go b/pkg/smartcontract/convertor.go index 680238f29..c592807b8 100644 --- a/pkg/smartcontract/convertor.go +++ b/pkg/smartcontract/convertor.go @@ -7,7 +7,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// ParameterFromStackItem converts stackitem.Item to Parameter +// ParameterFromStackItem converts stackitem.Item to Parameter. func ParameterFromStackItem(i stackitem.Item, seen map[stackitem.Item]bool) Parameter { switch t := i.(type) { case stackitem.Null, *stackitem.Pointer: diff --git a/pkg/smartcontract/param_type.go b/pkg/smartcontract/param_type.go index 2875e60bd..2ea611a95 100644 --- a/pkg/smartcontract/param_type.go +++ b/pkg/smartcontract/param_type.go @@ -38,7 +38,7 @@ const ( // fileBytesParamType is a string representation of `filebytes` parameter type used in cli. const fileBytesParamType string = "filebytes" -// validParamTypes contains a map of known ParamTypes +// validParamTypes contains a map of known ParamTypes. var validParamTypes = map[ParamType]bool{ UnknownType: true, AnyType: true, diff --git a/pkg/smartcontract/trigger/trigger_type.go b/pkg/smartcontract/trigger/trigger_type.go index 60f3c1b08..86a00ff39 100644 --- a/pkg/smartcontract/trigger/trigger_type.go +++ b/pkg/smartcontract/trigger/trigger_type.go @@ -40,7 +40,7 @@ const ( All Type = OnPersist | PostPersist | Verification | Application ) -// FromString converts string to trigger Type +// FromString converts string to trigger Type. func FromString(str string) (Type, error) { triggers := []Type{OnPersist, PostPersist, Verification, Application, All} str = strings.ToLower(str) diff --git a/pkg/util/uint256.go b/pkg/util/uint256.go index 9e3c0df2f..ff764d4da 100644 --- a/pkg/util/uint256.go +++ b/pkg/util/uint256.go @@ -63,7 +63,7 @@ func (u Uint256) BytesBE() []byte { return u[:] } -// Reverse reverses the Uint256 object +// Reverse reverses the Uint256 object. func (u Uint256) Reverse() Uint256 { res, _ := Uint256DecodeBytesLE(u.BytesBE()) return res diff --git a/pkg/vm/opcode/opcode.go b/pkg/vm/opcode/opcode.go index e1fd89a56..3d24b7ea7 100644 --- a/pkg/vm/opcode/opcode.go +++ b/pkg/vm/opcode/opcode.go @@ -7,7 +7,7 @@ type Opcode byte // Viable list of supported instruction constants. const ( - // Constants + // Constants. PUSHINT8 Opcode = 0x00 PUSHINT16 Opcode = 0x01 PUSHINT32 Opcode = 0x02 @@ -43,7 +43,7 @@ const ( PUSH15 Opcode = 0x1F PUSH16 Opcode = 0x20 - // Flow control + // Flow control. NOP Opcode = 0x21 JMP Opcode = 0x22 JMPL Opcode = 0x23 // JMP_L @@ -68,7 +68,7 @@ const ( CALLA Opcode = 0x36 CALLT Opcode = 0x37 - // Exceptions + // Exceptions. ABORT Opcode = 0x38 ASSERT Opcode = 0x39 THROW Opcode = 0x3A @@ -81,7 +81,7 @@ const ( RET Opcode = 0x40 SYSCALL Opcode = 0x41 - // Stack + // Stack. DEPTH Opcode = 0x43 DROP Opcode = 0x45 NIP Opcode = 0x46 @@ -98,7 +98,7 @@ const ( REVERSE4 Opcode = 0x54 REVERSEN Opcode = 0x55 - // Slots + // Slots. INITSSLOT Opcode = 0x56 INITSLOT Opcode = 0x57 LDSFLD0 Opcode = 0x58 @@ -150,7 +150,7 @@ const ( STARG6 Opcode = 0x86 STARG Opcode = 0x87 - // Splice + // Splice. NEWBUFFER Opcode = 0x88 MEMCPY Opcode = 0x89 CAT Opcode = 0x8B @@ -158,7 +158,7 @@ const ( LEFT Opcode = 0x8D RIGHT Opcode = 0x8E - // Bitwise logic + // Bitwise logic. INVERT Opcode = 0x90 AND Opcode = 0x91 OR Opcode = 0x92 @@ -166,7 +166,7 @@ const ( EQUAL Opcode = 0x97 NOTEQUAL Opcode = 0x98 - // Arithmetic + // Arithmetic. SIGN Opcode = 0x99 ABS Opcode = 0x9A NEGATE Opcode = 0x9B @@ -195,7 +195,7 @@ const ( MAX Opcode = 0xBA WITHIN Opcode = 0xBB - // Advanced data structures (arrays, structures, maps) + // Advanced data structures (arrays, structures, maps). PACK Opcode = 0xC0 UNPACK Opcode = 0xC1 NEWARRAY0 Opcode = 0xC2 @@ -216,7 +216,7 @@ const ( CLEARITEMS Opcode = 0xD3 POPITEM Opcode = 0xD4 - // Types + // Types. ISNULL Opcode = 0xD8 ISTYPE Opcode = 0xD9 CONVERT Opcode = 0xDB diff --git a/pkg/vm/stackitem/item.go b/pkg/vm/stackitem/item.go index a0f8ba061..a8af99573 100644 --- a/pkg/vm/stackitem/item.go +++ b/pkg/vm/stackitem/item.go @@ -980,12 +980,12 @@ func (p *Pointer) Convert(typ Type) (Item, error) { } } -// ScriptHash returns pointer item hash +// ScriptHash returns pointer item hash. func (p *Pointer) ScriptHash() util.Uint160 { return p.hash } -// Position returns pointer item position +// Position returns pointer item position. func (p *Pointer) Position() int { return p.pos } diff --git a/pkg/vm/vm.go b/pkg/vm/vm.go index 46f106482..f284d8c04 100644 --- a/pkg/vm/vm.go +++ b/pkg/vm/vm.go @@ -1487,7 +1487,7 @@ func getTryParams(op opcode.Opcode, p []byte) ([]byte, []byte) { return p[:i], p[i:] } -// getJumpCondition performs opcode specific comparison of a and b +// getJumpCondition performs opcode specific comparison of a and b. func getJumpCondition(op opcode.Opcode, a, b *big.Int) bool { cmp := a.Cmp(b) switch op { @@ -1790,17 +1790,17 @@ func bytesToPublicKey(b []byte, curve elliptic.Curve) *keys.PublicKey { return pkey } -// GetCallingScriptHash implements ScriptHashGetter interface +// GetCallingScriptHash implements ScriptHashGetter interface. func (v *VM) GetCallingScriptHash() util.Uint160 { return v.Context().callingScriptHash } -// GetEntryScriptHash implements ScriptHashGetter interface +// GetEntryScriptHash implements ScriptHashGetter interface. func (v *VM) GetEntryScriptHash() util.Uint160 { return v.getContextScriptHash(v.Istack().Len() - 1) } -// GetCurrentScriptHash implements ScriptHashGetter interface +// GetCurrentScriptHash implements ScriptHashGetter interface. func (v *VM) GetCurrentScriptHash() util.Uint160 { return v.getContextScriptHash(0) } diff --git a/pkg/vm/vm_test.go b/pkg/vm/vm_test.go index 2b3e97477..c70f9a282 100644 --- a/pkg/vm/vm_test.go +++ b/pkg/vm/vm_test.go @@ -641,7 +641,7 @@ func TestNOT(t *testing.T) { t.Run("Buffer1", getTestFuncForVM(prog, false, stackitem.NewBuffer([]byte{1}))) } -// getBigInt returns 2^a+b +// getBigInt returns 2^a+b. func getBigInt(a, b int64) *big.Int { p := new(big.Int).Exp(big.NewInt(2), big.NewInt(a), nil) p.Add(p, big.NewInt(b)) diff --git a/pkg/wallet/token.go b/pkg/wallet/token.go index 0c1e90e9f..ecea33f93 100644 --- a/pkg/wallet/token.go +++ b/pkg/wallet/token.go @@ -25,7 +25,7 @@ func NewToken(tokenHash util.Uint160, name, symbol string, decimals int64, stand } } -// Address returns token address from hash +// Address returns token address from hash. func (t *Token) Address() string { return address.Uint160ToString(t.Hash) } diff --git a/pkg/wallet/wallet.go b/pkg/wallet/wallet.go index 4b8bf364e..e365849fb 100644 --- a/pkg/wallet/wallet.go +++ b/pkg/wallet/wallet.go @@ -54,7 +54,7 @@ func NewWallet(location string) (*Wallet, error) { return newWallet(file), nil } -// NewWalletFromFile creates a Wallet from the given wallet file path +// NewWalletFromFile creates a Wallet from the given wallet file path. func NewWalletFromFile(path string) (*Wallet, error) { file, err := os.OpenFile(path, os.O_RDWR, os.ModeAppend) if err != nil { From c76f8b8fbe254160b3c2793d19aeb2bff60d753c Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 12 May 2021 23:25:06 +0300 Subject: [PATCH 33/34] Makefile: use golangci-lint instead of golint It includes golint and also has a lot of other useful linters. --- .circleci/config.yml | 4 ++-- .github/workflows/run_tests.yml | 25 +++++-------------------- Makefile | 2 +- 3 files changed, 8 insertions(+), 23 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 7b528d9eb..17e8ac260 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -41,8 +41,8 @@ jobs: - run: name: go-lint command: | - go get -u -v golang.org/x/lint/golint - golint -set_exit_status ./... + curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.40.0 + make lint vet: working_directory: /go/src/github.com/nspcc-dev/neo-go diff --git a/.github/workflows/run_tests.yml b/.github/workflows/run_tests.yml index 190770028..8fecf7582 100644 --- a/.github/workflows/run_tests.yml +++ b/.github/workflows/run_tests.yml @@ -16,29 +16,14 @@ env: jobs: lint: name: Lint - runs-on: ubuntu-18.04 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - - name: Set up Go - uses: actions/setup-go@v2 + - name: golangci-lint + uses: golangci/golangci-lint-action@v2 with: - go-version: 1.16 - - - name: Restore Go modules from cache - uses: actions/cache@v2 - with: - path: /home/runner/go/pkg/mod - key: deps-${{ hashFiles('go.sum') }} - - - name: Update Go modules - run: go mod download -json - - - name: Run linter - run: | - go get -u -v golang.org/x/lint/golint - make lint + version: latest vet: name: Vet @@ -189,4 +174,4 @@ jobs: run: go mod download -json - name: Build Docker image - run: make image \ No newline at end of file + run: make image diff --git a/Makefile b/Makefile index 06261b346..4ea0dc735 100644 --- a/Makefile +++ b/Makefile @@ -84,7 +84,7 @@ vet: @go vet ./... lint: - @go list ./... | xargs -L1 golint -set_exit_status + @golangci-lint run fmt: @gofmt -l -w -s $$(find . -type f -name '*.go'| grep -v "/vendor/") From 50cb0450f25d61d3a4bd5577de480a5a5348b212 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Thu, 13 May 2021 00:06:08 +0300 Subject: [PATCH 34/34] circleci/workflows: drop vet run golangci-lint already includes govet, so having it in a separate task doesn't add any value (only increases CI running time). --- .circleci/config.yml | 14 -------------- .github/workflows/run_tests.yml | 24 ------------------------ docs/release-instruction.md | 1 - 3 files changed, 39 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 17e8ac260..b2353748f 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -44,16 +44,6 @@ jobs: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.40.0 make lint - vet: - working_directory: /go/src/github.com/nspcc-dev/neo-go - executor: go1_16 - steps: - - checkout - - gomod - - run: - name: go-vet - command: go vet ./... - test_1_14: working_directory: /go/src/github.com/nspcc-dev/neo-go executor: go1_14 @@ -123,10 +113,6 @@ workflows: version: 2 workflow: jobs: - - vet: - filters: - tags: - only: v/[0-9]+\.[0-9]+\.[0-9]+/ - lint: filters: tags: diff --git a/.github/workflows/run_tests.yml b/.github/workflows/run_tests.yml index 8fecf7582..43d4587e3 100644 --- a/.github/workflows/run_tests.yml +++ b/.github/workflows/run_tests.yml @@ -25,30 +25,6 @@ jobs: with: version: latest - vet: - name: Vet - runs-on: ubuntu-18.04 - - steps: - - uses: actions/checkout@v2 - - - name: Set up Go - uses: actions/setup-go@v2 - with: - go-version: 1.16 - - - name: Restore Go modules from cache - uses: actions/cache@v2 - with: - path: /home/runner/go/pkg/mod - key: deps-${{ hashFiles('go.sum') }} - - - name: Update Go modules - run: go mod download -json - - - name: Run vet - run: go vet ./... - test_cover: name: Coverage runs-on: ubuntu-18.04 diff --git a/docs/release-instruction.md b/docs/release-instruction.md index bd02b1fc1..6310de5b9 100644 --- a/docs/release-instruction.md +++ b/docs/release-instruction.md @@ -8,7 +8,6 @@ list for a new release. These should run successfuly: * build * unit-tests - * vet * lint * privnet with consensus nodes