diff --git a/config/config.go b/config/config.go index 874de3238..b5738584c 100644 --- a/config/config.go +++ b/config/config.go @@ -111,7 +111,7 @@ func Load(path string, netMode NetMode) (Config, error) { ApplicationConfiguration: ApplicationConfiguration{}, } - err = yaml.Unmarshal([]byte(configData), &config) + err = yaml.Unmarshal(configData, &config) if err != nil { return Config{}, errors.Wrap(err, "Problem unmarshaling config json data") } diff --git a/pkg/core/asset_state.go b/pkg/core/asset_state.go index f927e4e0d..2bbfbf7b7 100644 --- a/pkg/core/asset_state.go +++ b/pkg/core/asset_state.go @@ -29,7 +29,7 @@ func (a Assets) commit(b storage.Batch) error { return nil } -// AssetState represents the state of an NEO registerd Asset. +// AssetState represents the state of an NEO registered Asset. type AssetState struct { ID util.Uint256 AssetType transaction.AssetType diff --git a/pkg/core/blockchain.go b/pkg/core/blockchain.go index 2d415ffbc..7ed7493f2 100644 --- a/pkg/core/blockchain.go +++ b/pkg/core/blockchain.go @@ -510,7 +510,7 @@ func (bc *Blockchain) HasBlock(hash util.Uint256) bool { return false } -// CurrentBlockHash returns the heighest processed block hash. +// CurrentBlockHash returns the highest processed block hash. func (bc *Blockchain) CurrentBlockHash() (hash util.Uint256) { bc.headersOp <- func(headerList *HeaderHashList) { hash = headerList.Get(int(bc.BlockHeight())) @@ -553,8 +553,7 @@ func (bc *Blockchain) GetAssetState(assetID util.Uint256) *AssetState { var as *AssetState bc.Store.Seek(storage.STAsset.Bytes(), func(k, v []byte) { var a AssetState - a.DecodeBinary(bytes.NewReader(v)) - if a.ID == assetID { + if err := a.DecodeBinary(bytes.NewReader(v)); err == nil && a.ID == assetID { as = &a } }) diff --git a/pkg/core/header_test.go b/pkg/core/header_test.go index fd2812767..f9dff4eb7 100644 --- a/pkg/core/header_test.go +++ b/pkg/core/header_test.go @@ -52,10 +52,10 @@ func TestHeaderEncodeDecode(t *testing.T) { if !header.NextConsensus.Equals(headerDecode.NextConsensus) { t.Fatalf("expected both next consensus fields to be equal") } - if bytes.Compare(header.Script.InvocationScript, headerDecode.Script.InvocationScript) != 0 { + if !bytes.Equal(header.Script.InvocationScript, headerDecode.Script.InvocationScript) { t.Fatalf("expected equal invocation scripts %v and %v", header.Script.InvocationScript, headerDecode.Script.InvocationScript) } - if bytes.Compare(header.Script.VerificationScript, headerDecode.Script.VerificationScript) != 0 { + if !bytes.Equal(header.Script.VerificationScript, headerDecode.Script.VerificationScript) { t.Fatalf("expected equal verification scripts %v and %v", header.Script.VerificationScript, headerDecode.Script.VerificationScript) } } diff --git a/pkg/core/storage/helpers.go b/pkg/core/storage/helpers.go index 1b2bf774c..6ba5b97a1 100644 --- a/pkg/core/storage/helpers.go +++ b/pkg/core/storage/helpers.go @@ -73,10 +73,7 @@ func HeaderHashes(s Store) ([]util.Uint256, error) { sort.Sort(uint32Slice(sortedKeys)) for _, key := range sortedKeys { - values := hashMap[key] - for _, hash := range values { - hashes = append(hashes, hash) - } + hashes = append(hashes, hashMap[key]...) } return hashes, nil diff --git a/pkg/core/storage/memory_store.go b/pkg/core/storage/memory_store.go index fa57505c0..de705a911 100644 --- a/pkg/core/storage/memory_store.go +++ b/pkg/core/storage/memory_store.go @@ -41,13 +41,13 @@ func (s *MemoryStore) Get(key []byte) ([]byte, error) { return nil, ErrKeyNotFound } -// Put implementes the Store interface. +// Put implements the Store interface. func (s *MemoryStore) Put(key, value []byte) error { s.mem[makeKey(key)] = value return nil } -// PutBatch implementes the Store interface. +// PutBatch implements the Store interface. func (s *MemoryStore) PutBatch(batch Batch) error { b := batch.(*MemoryBatch) for k, v := range b.m { @@ -58,7 +58,7 @@ func (s *MemoryStore) PutBatch(batch Batch) error { return nil } -// Seek implementes the Store interface. +// Seek implements the Store interface. func (s *MemoryStore) Seek(key []byte, f func(k, v []byte)) { } diff --git a/pkg/crypto/base58.go b/pkg/crypto/base58.go index 867a231da..3f967d965 100644 --- a/pkg/crypto/base58.go +++ b/pkg/crypto/base58.go @@ -57,7 +57,7 @@ func Base58Decode(s string) ([]byte, error) { out := n.Bytes() buf := make([]byte, zero+len(out)) - copy(buf[zero:], out[:]) + copy(buf[zero:], out) return buf, nil } @@ -100,14 +100,18 @@ func Base58CheckDecode(s string) (b []byte, err error) { } sha := sha256.New() - sha.Write(b[:len(b)-4]) + if _, err = sha.Write(b[:len(b)-4]); err != nil { + return nil, err + } hash := sha.Sum(nil) sha.Reset() - sha.Write(hash) + if _, err = sha.Write(hash); err != nil { + return nil, err + } hash = sha.Sum(nil) - if bytes.Compare(hash[0:4], b[len(b)-4:]) != 0 { + if !bytes.Equal(hash[0:4], b[len(b)-4:]) { return nil, errors.New("invalid base-58 check string: invalid checksum.") } diff --git a/pkg/crypto/elliptic_curve.go b/pkg/crypto/elliptic_curve.go index 7868a597a..c2b2edebc 100644 --- a/pkg/crypto/elliptic_curve.go +++ b/pkg/crypto/elliptic_curve.go @@ -167,10 +167,7 @@ func (c *EllipticCurve) IsOnCurve(P ECPoint) bool { mulMod(c.A, P.X, c.P), c.P), c.B, c.P) - if lhs.Cmp(rhs) == 0 { - return true - } - return false + return lhs.Cmp(rhs) == 0 } // Add computes R = P + Q on EllipticCurve ec. diff --git a/pkg/network/discovery.go b/pkg/network/discovery.go index f8c7010f9..0257877a3 100644 --- a/pkg/network/discovery.go +++ b/pkg/network/discovery.go @@ -80,7 +80,7 @@ func (d *DefaultDiscovery) RegisterBadAddr(addr string) { // UnconnectedPeers returns all addresses of unconnected addrs. func (d *DefaultDiscovery) UnconnectedPeers() []string { - var addrs []string + addrs := make([]string, 0, len(d.unconnectedAddrs)) for addr := range d.unconnectedAddrs { addrs = append(addrs, addr) } @@ -89,7 +89,7 @@ func (d *DefaultDiscovery) UnconnectedPeers() []string { // BadPeers returns all addresses of bad addrs. func (d *DefaultDiscovery) BadPeers() []string { - var addrs []string + addrs := make([]string, 0, len(d.badAddrs)) for addr := range d.badAddrs { addrs = append(addrs, addr) } diff --git a/pkg/network/server.go b/pkg/network/server.go index f4d8ad688..f7160c6da 100644 --- a/pkg/network/server.go +++ b/pkg/network/server.go @@ -56,7 +56,7 @@ type ( ) // NewServer returns a new Server, initialized with the given configuration. -func NewServer(config ServerConfig, chain *core.Blockchain) *Server { +func NewServer(config ServerConfig, chain core.Blockchainer) *Server { s := &Server{ ServerConfig: config, chain: chain, @@ -129,7 +129,11 @@ func (s *Server) run() { return case p := <-s.register: // When a new peer is connected we send out our version immediately. - s.sendVersion(p) + if err := s.sendVersion(p); err != nil { + log.WithFields(log.Fields{ + "endpoint": p.Endpoint(), + }).Error(err) + } s.peers[p] = true log.WithFields(log.Fields{ "endpoint": p.Endpoint(), @@ -258,9 +262,9 @@ func (s *Server) requestHeaders(p Peer) { // send at once. func (s *Server) requestBlocks(p Peer) { var ( + hashes []util.Uint256 hashStart = s.chain.BlockHeight() + 1 headerHeight = s.chain.HeaderHeight() - hashes = []util.Uint256{} ) for hashStart < headerHeight && len(hashes) < maxBlockBatch { hash := s.chain.GetHeaderHash(int(hashStart)) diff --git a/pkg/network/server_config.go b/pkg/network/server_config.go index b3f46ef2a..434ecbc96 100644 --- a/pkg/network/server_config.go +++ b/pkg/network/server_config.go @@ -26,7 +26,7 @@ type ( // ModeMainNet NEO main network. Net config.NetMode - // Relay determins whether the server is forwarding its inventory. + // Relay determines whether the server is forwarding its inventory. Relay bool // Seeds are a list of initial nodes used to establish connectivity. diff --git a/pkg/rpc/README.md b/pkg/rpc/README.md index 9633992c5..2a2fe0d55 100644 --- a/pkg/rpc/README.md +++ b/pkg/rpc/README.md @@ -66,7 +66,7 @@ The server is written to support as much of the [JSON-RPC 2.0 Spec](http://www.j An example would be viewing the version of the node: ```bash -curl -X POST -d '{"jsonrpc": "2.0", "method": "getversion", "params": [], "id": 1}" http://localhost:20332 +$ curl -X POST -d '{"jsonrpc": "2.0", "method": "getversion", "params": [], "id": 1}' http://localhost:20332 ``` which would yield the response: diff --git a/pkg/rpc/server_test.go b/pkg/rpc/server_test.go index 520e97ea1..ea73bd7fe 100644 --- a/pkg/rpc/server_test.go +++ b/pkg/rpc/server_test.go @@ -7,6 +7,7 @@ import ( "net/http" "net/http/httptest" "strconv" + "strings" "testing" "github.com/CityOfZion/neo-go/config" @@ -108,9 +109,7 @@ func TestHandler(t *testing.T) { for _, tc := range testCases { t.Run(fmt.Sprintf("method: %s, rpc call: %s", tc.method, tc.rpcCall), func(t *testing.T) { - jsonStr := []byte(tc.rpcCall) - - req := httptest.NewRequest("POST", "http://0.0.0.0:20333/", bytes.NewBuffer(jsonStr)) + req := httptest.NewRequest("POST", "http://0.0.0.0:20333/", strings.NewReader(tc.rpcCall)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() diff --git a/pkg/util/array_test.go b/pkg/util/array_test.go index c75e7421e..dae4fc65a 100644 --- a/pkg/util/array_test.go +++ b/pkg/util/array_test.go @@ -14,7 +14,7 @@ func TestArrayReverse(t *testing.T) { } } -// This tests a bug that occured with arrays of size 1 +// This tests a bug that occurred with arrays of size 1 func TestArrayReverseLen2(t *testing.T) { arr := []byte{0x01} have := ArrayReverse(arr) diff --git a/pkg/util/endpoint.go b/pkg/util/endpoint.go index bfbb9831b..afdf320e0 100644 --- a/pkg/util/endpoint.go +++ b/pkg/util/endpoint.go @@ -43,7 +43,7 @@ func (e Endpoint) Network() string { return "tcp" } func (e Endpoint) String() string { b := make([]uint8, 4) for i := 0; i < 4; i++ { - b[i] = byte(e.IP[len(e.IP)-4+i]) + b[i] = e.IP[len(e.IP)-4+i] } return fmt.Sprintf("%d.%d.%d.%d:%d", b[0], b[1], b[2], b[3], e.Port) } diff --git a/pkg/vm/cli/cli.go b/pkg/vm/cli/cli.go index ed996fa89..ebeb2da71 100644 --- a/pkg/vm/cli/cli.go +++ b/pkg/vm/cli/cli.go @@ -230,7 +230,7 @@ func parseArgs(args []string) ([]vm.StackItem, error) { func printHelp() { names := make([]string, len(commands)) i := 0 - for name, _ := range commands { + for name := range commands { names[i] = name i++ } diff --git a/pkg/vm/compiler/analysis.go b/pkg/vm/compiler/analysis.go index aacadd5ef..039a07a45 100644 --- a/pkg/vm/compiler/analysis.go +++ b/pkg/vm/compiler/analysis.go @@ -54,7 +54,7 @@ func typeAndValueForField(fld *types.Var) types.TypeAndValue { // countGlobals counts the global variables in the program to add // them with the stacksize of the function. -func countGlobals(f *ast.File) (i int64) { +func countGlobals(f ast.Node) (i int64) { ast.Inspect(f, func(node ast.Node) bool { switch node.(type) { // Skip all functio declarations. @@ -78,11 +78,12 @@ func isIdentBool(ident *ast.Ident) bool { // makeBoolFromIdent creates a bool type from an *ast.Ident. func makeBoolFromIdent(ident *ast.Ident, tinfo *types.Info) types.TypeAndValue { var b bool - if ident.Name == "true" { + switch ident.Name { + case "true": b = true - } else if ident.Name == "false" { + case "false": b = false - } else { + default: log.Fatalf("givent identifier cannot be converted to a boolean => %s", ident.Name) } return types.TypeAndValue{ @@ -132,7 +133,7 @@ func (f funcUsage) funcUsed(name string) bool { } // hasReturnStmt look if the given FuncDecl has a return statement. -func hasReturnStmt(decl *ast.FuncDecl) (b bool) { +func hasReturnStmt(decl ast.Node) (b bool) { ast.Inspect(decl, func(node ast.Node) bool { if _, ok := node.(*ast.ReturnStmt); ok { b = true diff --git a/pkg/vm/compiler/codegen.go b/pkg/vm/compiler/codegen.go index c8affaf04..e8ac49cfa 100644 --- a/pkg/vm/compiler/codegen.go +++ b/pkg/vm/compiler/codegen.go @@ -124,7 +124,7 @@ func (c *codegen) emitStoreStructField(i int) { // convertGlobals will traverse the AST and only convert global declarations. // If we call this in convertFuncDecl then it will load all global variables // into the scope of the function. -func (c *codegen) convertGlobals(f *ast.File) { +func (c *codegen) convertGlobals(f ast.Node) { ast.Inspect(f, func(node ast.Node) bool { switch n := node.(type) { case *ast.FuncDecl: @@ -136,7 +136,7 @@ func (c *codegen) convertGlobals(f *ast.File) { }) } -func (c *codegen) convertFuncDecl(file *ast.File, decl *ast.FuncDecl) { +func (c *codegen) convertFuncDecl(file ast.Node, decl *ast.FuncDecl) { var ( f *funcScope ok bool @@ -428,13 +428,14 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor { emitOpcode(c.prog, vm.Onop) // Check builtin first to avoid nil pointer on funcScope! - if isBuiltin { + switch { + case isBuiltin: // Use the ident to check, builtins are not in func scopes. // We can be sure builtins are of type *ast.Ident. c.convertBuiltin(n) - } else if isSyscall(f.name) { + case isSyscall(f.name): c.convertSyscall(f.name) - } else { + default: emitCall(c.prog, vm.Ocall, int16(f.label)) } diff --git a/pkg/vm/compiler/emit.go b/pkg/vm/compiler/emit.go index 1dee56228..3221ac745 100644 --- a/pkg/vm/compiler/emit.go +++ b/pkg/vm/compiler/emit.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "errors" "fmt" + "io" "math/big" "github.com/CityOfZion/neo-go/pkg/util" @@ -19,11 +20,11 @@ func emit(w *bytes.Buffer, op vm.Opcode, b []byte) error { return err } -func emitOpcode(w *bytes.Buffer, op vm.Opcode) error { +func emitOpcode(w io.ByteWriter, op vm.Opcode) error { return w.WriteByte(byte(op)) } -func emitBool(w *bytes.Buffer, ok bool) error { +func emitBool(w io.ByteWriter, ok bool) error { if ok { return emitOpcode(w, vm.Opusht) } @@ -57,15 +58,16 @@ func emitBytes(w *bytes.Buffer, b []byte) error { n = len(b) ) - if n <= int(vm.Opushbytes75) { + switch { + case n <= int(vm.Opushbytes75): return emit(w, vm.Opcode(n), b) - } else if n < 0x100 { + case n < 0x100: err = emit(w, vm.Opushdata1, []byte{byte(n)}) - } else if n < 0x10000 { + case n < 0x10000: buf := make([]byte, 2) binary.LittleEndian.PutUint16(buf, uint16(n)) err = emit(w, vm.Opushdata2, buf) - } else { + default: buf := make([]byte, 4) binary.LittleEndian.PutUint32(buf, uint32(n)) err = emit(w, vm.Opushdata4, buf) diff --git a/pkg/vm/emit.go b/pkg/vm/emit.go index 56f8bb8cb..49b794e86 100644 --- a/pkg/vm/emit.go +++ b/pkg/vm/emit.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "errors" "fmt" + "io" "math/big" "github.com/CityOfZion/neo-go/pkg/util" @@ -20,12 +21,12 @@ func Emit(w *bytes.Buffer, op Opcode, b []byte) error { } // EmitOpcode emits a single VM Opcode the given buffer. -func EmitOpcode(w *bytes.Buffer, op Opcode) error { +func EmitOpcode(w io.ByteWriter, op Opcode) error { return w.WriteByte(byte(op)) } // EmitBool emits a bool type the given buffer. -func EmitBool(w *bytes.Buffer, ok bool) error { +func EmitBool(w io.ByteWriter, ok bool) error { if ok { return EmitOpcode(w, Opusht) } @@ -90,7 +91,7 @@ func EmitSyscall(w *bytes.Buffer, api string) error { } buf := make([]byte, len(api)+1) buf[0] = byte(len(api)) - copy(buf[1:len(buf)], []byte(api)) + copy(buf[1:], []byte(api)) return Emit(w, Osyscall, buf) } @@ -102,7 +103,7 @@ func EmitCall(w *bytes.Buffer, op Opcode, label int16) error { // EmitJmp emits a jump Opcode along with label to the given buffer. func EmitJmp(w *bytes.Buffer, op Opcode, label int16) error { if !isOpcodeJmp(op) { - return fmt.Errorf("opcode %s is not a jump or call type", op) + return fmt.Errorf("opcode %s is not a jump or call type", op.String()) } buf := make([]byte, 2) binary.LittleEndian.PutUint16(buf, uint16(label)) diff --git a/pkg/vm/stack.go b/pkg/vm/stack.go index 80d139324..276388e37 100644 --- a/pkg/vm/stack.go +++ b/pkg/vm/stack.go @@ -33,7 +33,7 @@ type Element struct { stack *Stack } -// NewElement returns a new Element object, with its underlying value infered +// NewElement returns a new Element object, with its underlying value inferred // to the corresponding type. func NewElement(v interface{}) *Element { return &Element{ diff --git a/pkg/vm/syscall.go b/pkg/vm/syscall.go index 2e9c30260..69f2ee1e3 100644 --- a/pkg/vm/syscall.go +++ b/pkg/vm/syscall.go @@ -1,7 +1,7 @@ package vm // Syscalls are a mapping between the syscall function name -// and the registerd VM interop API. +// and the registered VM interop API. var Syscalls = map[string]string{ // Storage API "GetContext": "Neo.Storage.GetContext", diff --git a/pkg/vm/vm.go b/pkg/vm/vm.go index 2c0dcd7a5..c48b6c0d6 100644 --- a/pkg/vm/vm.go +++ b/pkg/vm/vm.go @@ -87,7 +87,7 @@ func (v *VM) LoadArgs(method []byte, args []StackItem) { v.estack.PushVal(args) } if method != nil { - v.estack.PushVal([]byte(method)) + v.estack.PushVal(method) } } @@ -104,7 +104,7 @@ func (v *VM) PrintOps() { } else { cursor = "" } - fmt.Fprintf(w, "%d\t0x%2x\t%s\t%s\n", i, prog[i], Opcode(prog[i]), cursor) + fmt.Fprintf(w, "%d\t0x%2x\t%s\t%s\n", i, prog[i], Opcode(prog[i]).String(), cursor) } w.Flush() @@ -142,7 +142,7 @@ func (v *VM) Load(prog []byte) { } // LoadScript will load a script from the internal script table. It -// will immediatly push a new context created from this script to +// will immediately push a new context created from this script to // the invocation stack and starts executing it. func (v *VM) LoadScript(b []byte) { ctx := NewContext(b) @@ -203,7 +203,7 @@ func (v *VM) Run() { case breakState: ctx := v.Context() i, op := ctx.CurrInstr() - fmt.Printf("at breakpoint %d (%s)\n", i, op) + fmt.Printf("at breakpoint %d (%s)\n", i, op.String()) return case faultState: fmt.Println("FAULT") @@ -229,7 +229,7 @@ func (v *VM) Step() { // execute performs an instruction cycle in the VM. Acting on the instruction (opcode). func (v *VM) execute(ctx *Context, op Opcode) { - // Instead of poluting the whole VM logic with error handling, we will recover + // Instead of polluting the whole VM logic with error handling, we will recover // each panic at a central point, putting the VM in a fault state. defer func() { if err := recover(); err != nil { @@ -713,7 +713,7 @@ func (v *VM) execute(ctx *Context, op Opcode) { } default: - panic(fmt.Sprintf("unknown opcode %s", op)) + panic(fmt.Sprintf("unknown opcode %s", op.String())) } } diff --git a/pkg/wallet/wallet.go b/pkg/wallet/wallet.go index 6211d0e32..a0d472e82 100644 --- a/pkg/wallet/wallet.go +++ b/pkg/wallet/wallet.go @@ -16,13 +16,13 @@ type Wallet struct { // Version of the wallet, used for later upgrades. Version string `json:"version"` - // A list of accounts which decribes the details of each account + // A list of accounts which describes the details of each account // in the wallet. Accounts []*Account `json:"accounts"` Scrypt scryptParams `json:"scrypt"` - // Extra metadata can be used for storing abritrary data. + // Extra metadata can be used for storing arbitrary data. // This field can be empty. Extra interface{} `json:"extra"`