Fix typos and warnings for GoReport / GolangCiLinter (#132)

- typos
- gofmt -s
- govet warnings
- golangci-lint run
This commit is contained in:
Evgeniy Kulikov 2019-02-09 18:53:58 +03:00 committed by fabwa
parent d183ea3c1f
commit 630919bf7d
24 changed files with 70 additions and 65 deletions

View file

@ -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")
}

View file

@ -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

View file

@ -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
}
})

View file

@ -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)
}
}

View file

@ -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

View file

@ -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)) {
}

View file

@ -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.")
}

View file

@ -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.

View file

@ -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)
}

View file

@ -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))

View file

@ -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.

View file

@ -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:

View file

@ -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()

View file

@ -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)

View file

@ -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)
}

View file

@ -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++
}

View file

@ -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

View file

@ -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))
}

View file

@ -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)

View file

@ -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))

View file

@ -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{

View file

@ -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",

View file

@ -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()))
}
}

View file

@ -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"`