[FIX] Formatting and code-style (#118)

* [FIX] Formatting and code-style

- gofmt
- import resort
- prealloc slices
- simplify code

* fix vet
This commit is contained in:
Evgeniy Kulikov 2019-01-25 14:20:35 +03:00 committed by fabwa
parent df2e9f68ef
commit f000b76879
37 changed files with 145 additions and 124 deletions

View file

@ -22,5 +22,7 @@ func main() {
vm.NewCommand(), vm.NewCommand(),
} }
ctl.Run(os.Args) if err := ctl.Run(os.Args); err != nil {
panic(err)
}
} }

View file

@ -8,8 +8,6 @@ import (
"time" "time"
"github.com/CityOfZion/neo-go/config" "github.com/CityOfZion/neo-go/config"
//"github.com/CityOfZion/neo-go/pkg/core"
"github.com/CityOfZion/neo-go/pkg/core/storage" "github.com/CityOfZion/neo-go/pkg/core/storage"
"github.com/CityOfZion/neo-go/pkg/core/transaction" "github.com/CityOfZion/neo-go/pkg/core/transaction"
"github.com/CityOfZion/neo-go/pkg/util" "github.com/CityOfZion/neo-go/pkg/util"
@ -104,7 +102,9 @@ func (bc *Blockchain) init() error {
ver, err := storage.Version(bc.Store) ver, err := storage.Version(bc.Store)
if err != nil { if err != nil {
log.Infof("no storage version found! creating genesis block") log.Infof("no storage version found! creating genesis block")
storage.PutVersion(bc.Store, version) if err = storage.PutVersion(bc.Store, version); err != nil {
return err
}
return bc.persistBlock(genesisBlock) return bc.persistBlock(genesisBlock)
} }
if ver != version { if ver != version {
@ -284,11 +284,17 @@ func (bc *Blockchain) persistBlock(block *Block) error {
assets = make(Assets) assets = make(Assets)
) )
storeAsBlock(batch, block, 0) if err := storeAsBlock(batch, block, 0); err != nil {
return err
}
storeAsCurrentBlock(batch, block) storeAsCurrentBlock(batch, block)
for _, tx := range block.Transactions { for _, tx := range block.Transactions {
storeAsTransaction(batch, tx, block.Index) if err := storeAsTransaction(batch, tx, block.Index); err != nil {
return err
}
unspentCoins[tx.Hash()] = NewUnspentCoinState(len(tx.Outputs)) unspentCoins[tx.Hash()] = NewUnspentCoinState(len(tx.Outputs))
// Process TX outputs. // Process TX outputs.

View file

@ -21,7 +21,10 @@ func (h *Header) DecodeBinary(r io.Reader) error {
} }
var padding uint8 var padding uint8
binary.Read(r, binary.LittleEndian, &padding) if err := binary.Read(r, binary.LittleEndian, &padding); err != nil {
return err
}
if padding != 0 { if padding != 0 {
return fmt.Errorf("format error: padding must equal 0 got %d", padding) return fmt.Errorf("format error: padding must equal 0 got %d", padding)
} }

View file

@ -51,7 +51,9 @@ func (s *MemoryStore) Put(key, value []byte) error {
func (s *MemoryStore) PutBatch(batch Batch) error { func (s *MemoryStore) PutBatch(batch Batch) error {
b := batch.(*MemoryBatch) b := batch.(*MemoryBatch)
for k, v := range b.m { for k, v := range b.m {
s.Put(*k, v) if err := s.Put(*k, v); err != nil {
return err
}
} }
return nil return nil
} }

View file

@ -13,7 +13,9 @@ func TestGetPut(t *testing.T) {
value = []byte("rocks") value = []byte("rocks")
) )
s.Put(key, value) if err := s.Put(key, value); err != nil {
t.Fatal(err)
}
newVal, err := s.Get(key) newVal, err := s.Get(key)
if err != nil { if err != nil {
@ -43,7 +45,10 @@ func TestPutBatch(t *testing.T) {
batch.Put(key, value) batch.Put(key, value)
s.PutBatch(batch) if err := s.PutBatch(batch); err != nil {
t.Fatal(err)
}
newVal, err := s.Get(key) newVal, err := s.Get(key)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View file

@ -89,7 +89,9 @@ func createGenesisBlock(cfg config.ProtocolConfiguration) (*Block, error) {
}, },
} }
block.rebuildMerkleRoot() if err = block.rebuildMerkleRoot(); err != nil {
return nil, err
}
return block, nil return block, nil
} }

View file

@ -5,6 +5,8 @@ import (
"crypto/sha256" "crypto/sha256"
"fmt" "fmt"
"math/big" "math/big"
"github.com/pkg/errors"
) )
const prefix rune = '1' const prefix rune = '1'
@ -54,7 +56,7 @@ func Base58Decode(s string) ([]byte, error) {
} }
out := n.Bytes() out := n.Bytes()
buf := make([]byte, (zero + len(out))) buf := make([]byte, zero+len(out))
copy(buf[zero:], out[:]) copy(buf[zero:], out[:])
return buf, nil return buf, nil
@ -94,7 +96,7 @@ func Base58CheckDecode(s string) (b []byte, err error) {
} }
if len(b) < 5 { if len(b) < 5 {
return nil, fmt.Errorf("Invalid base-58 check string: missing checksum.") return nil, errors.New("invalid base-58 check string: missing checksum.")
} }
sha := sha256.New() sha := sha256.New()
@ -106,7 +108,7 @@ func Base58CheckDecode(s string) (b []byte, err error) {
hash = sha.Sum(nil) hash = sha.Sum(nil)
if bytes.Compare(hash[0:4], b[len(b)-4:]) != 0 { if bytes.Compare(hash[0:4], b[len(b)-4:]) != 0 {
return nil, fmt.Errorf("Invalid base-58 check string: invalid checksum.") return nil, errors.New("invalid base-58 check string: invalid checksum.")
} }
// Strip the 4 byte long hash. // Strip the 4 byte long hash.

View file

@ -260,7 +260,7 @@ func cmdToByteArray(cmd CommandType) [cmdSize]byte {
} }
func cmdByteArrayToString(cmd [cmdSize]byte) string { func cmdByteArrayToString(cmd [cmdSize]byte) string {
buf := []byte{} buf := make([]byte, 0, cmdSize)
for i := 0; i < cmdSize; i++ { for i := 0; i < cmdSize; i++ {
if cmd[i] != 0 { if cmd[i] != 0 {
buf = append(buf, cmd[i]) buf = append(buf, cmd[i])

View file

@ -11,7 +11,7 @@ import (
func TestHeadersEncodeDecode(t *testing.T) { func TestHeadersEncodeDecode(t *testing.T) {
headers := &Headers{[]*core.Header{ headers := &Headers{[]*core.Header{
&core.Header{ {
BlockBase: core.BlockBase{ BlockBase: core.BlockBase{
Version: 0, Version: 0,
Index: 1, Index: 1,
@ -20,7 +20,7 @@ func TestHeadersEncodeDecode(t *testing.T) {
VerificationScript: []byte{0x1}, VerificationScript: []byte{0x1},
}, },
}}, }},
&core.Header{ {
BlockBase: core.BlockBase{ BlockBase: core.BlockBase{
Version: 0, Version: 0,
Index: 2, Index: 2,
@ -29,7 +29,7 @@ func TestHeadersEncodeDecode(t *testing.T) {
VerificationScript: []byte{0x1}, VerificationScript: []byte{0x1},
}, },
}}, }},
&core.Header{ {
BlockBase: core.BlockBase{ BlockBase: core.BlockBase{
Version: 0, Version: 0,
Index: 3, Index: 3,

View file

@ -242,8 +242,7 @@ func (s *Server) handleInvCmd(p Peer, inv *payload.Inventory) error {
return errInvalidInvType return errInvalidInvType
} }
payload := payload.NewInventory(inv.Type, inv.Hashes) payload := payload.NewInventory(inv.Type, inv.Hashes)
p.WriteMsg(NewMessage(s.Net, CMDGetData, payload)) return p.WriteMsg(NewMessage(s.Net, CMDGetData, payload))
return nil
} }
// requestHeaders will send a getheaders message to the peer. // requestHeaders will send a getheaders message to the peer.

View file

@ -56,8 +56,8 @@ func NewServerConfig(cfg config.Config) ServerConfig {
Net: protoConfig.Magic, Net: protoConfig.Magic,
Relay: appConfig.Relay, Relay: appConfig.Relay,
Seeds: protoConfig.SeedList, Seeds: protoConfig.SeedList,
DialTimeout: (appConfig.DialTimeout * time.Second), DialTimeout: appConfig.DialTimeout * time.Second,
ProtoTickInterval: (appConfig.ProtoTickInterval * time.Second), ProtoTickInterval: appConfig.ProtoTickInterval * time.Second,
MaxPeers: appConfig.MaxPeers, MaxPeers: appConfig.MaxPeers,
} }
} }

View file

@ -28,7 +28,9 @@ func TestSendVersion(t *testing.T) {
assert.Equal(t, uint32(0), version.StartHeight) assert.Equal(t, uint32(0), version.StartHeight)
} }
s.sendVersion(p) if err := s.sendVersion(p); err != nil {
t.Fatal(err)
}
} }
// Server should reply with a verack after receiving a valid version. // Server should reply with a verack after receiving a valid version.

View file

@ -128,7 +128,7 @@ func (c *Client) performRequest(method string, p params, v interface{}) error {
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Remote responded with a non 200 response: %d", resp.StatusCode) return fmt.Errorf("remote responded with a non 200 response: %d", resp.StatusCode)
} }
return json.NewDecoder(resp.Body).Decode(v) return json.NewDecoder(resp.Body).Decode(v)

View file

@ -29,12 +29,7 @@ func (s NeoScanServer) GetBalance(address string) ([]*Unspent, error) {
return nil, errs.Wrap(err, "Failed to perform HTTP request") return nil, errs.Wrap(err, "Failed to perform HTTP request")
} }
defer func() error { defer res.Body.Close()
if err := res.Body.Close(); err != nil {
return err
}
return nil
}()
if err = json.NewDecoder(res.Body).Decode(&balance); err != nil { if err = json.NewDecoder(res.Body).Decode(&balance); err != nil {
return nil, errs.Wrap(err, "Failed to decode HTTP response") return nil, errs.Wrap(err, "Failed to decode HTTP response")
@ -78,7 +73,7 @@ func (s NeoScanServer) CalculateInputs(address string, assetIdUint util.Uint256,
num++ num++
} }
if selected < required { if selected < required {
return nil, util.Fixed8(0), errors.New("Cannot compose inputs for transaction; check sender balance") return nil, util.Fixed8(0), errors.New("cannot compose inputs for transaction; check sender balance")
} }
inputs := make([]transaction.Input, 0, num) inputs := make([]transaction.Input, 0, num)

View file

@ -6,6 +6,7 @@ import (
"io" "io"
"net/http" "net/http"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -47,11 +48,11 @@ func (r *Request) DecodeData(data io.ReadCloser) error {
err := json.NewDecoder(data).Decode(r) err := json.NewDecoder(data).Decode(r)
if err != nil { if err != nil {
return fmt.Errorf("Error parsing JSON payload: %s", err) return errors.Errorf("error parsing JSON payload: %s", err)
} }
if r.JSONRPC != jsonRPCVersion { if r.JSONRPC != jsonRPCVersion {
return fmt.Errorf("Invalid version, expected 2.0 got: '%s'", r.JSONRPC) return errors.Errorf("invalid version, expected 2.0 got: '%s'", r.JSONRPC)
} }
return nil return nil
@ -64,7 +65,7 @@ func (r *Request) Params() (*Params, error) {
err := json.Unmarshal(r.RawParams, &params) err := json.Unmarshal(r.RawParams, &params)
if err != nil { if err != nil {
return nil, fmt.Errorf("Error parsing params field in payload: %s", err) return nil, errors.Errorf("error parsing params field in payload: %s", err)
} }
return &params, nil return &params, nil

View file

@ -5,6 +5,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"net/http" "net/http"
"strconv"
"github.com/CityOfZion/neo-go/pkg/core" "github.com/CityOfZion/neo-go/pkg/core"
"github.com/CityOfZion/neo-go/pkg/network" "github.com/CityOfZion/neo-go/pkg/network"
@ -33,7 +34,7 @@ var (
func NewServer(chain core.Blockchainer, port uint16, coreServer *network.Server) Server { func NewServer(chain core.Blockchainer, port uint16, coreServer *network.Server) Server {
return Server{ return Server{
Server: &http.Server{ Server: &http.Server{
Addr: fmt.Sprintf(":%d", port), Addr: ":" + strconv.FormatUint(uint64(port), 10),
}, },
chain: chain, chain: chain,
coreServer: coreServer, coreServer: coreServer,

View file

@ -9,9 +9,8 @@ import (
"strconv" "strconv"
"testing" "testing"
"github.com/CityOfZion/neo-go/pkg/core"
"github.com/CityOfZion/neo-go/config" "github.com/CityOfZion/neo-go/config"
"github.com/CityOfZion/neo-go/pkg/core"
"github.com/CityOfZion/neo-go/pkg/network" "github.com/CityOfZion/neo-go/pkg/network"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -25,12 +24,12 @@ func TestHandler(t *testing.T) {
cfg, err := config.Load(configPath, net) cfg, err := config.Load(configPath, net)
if err != nil { if err != nil {
t.Errorf("could not load configuration file") t.Fatal("could not create levelDB chain", err)
} }
chain, err := core.NewBlockchainLevelDB(cfg) chain, err := core.NewBlockchainLevelDB(cfg)
if err != nil { if err != nil {
t.Errorf("could not create levelDB chain") t.Fatal("could not create levelDB chain", err)
} }
serverConfig := network.NewServerConfig(cfg) serverConfig := network.NewServerConfig(cfg)

View file

@ -84,16 +84,16 @@ func StackParamTypeFromString(s string) (StackParamType, error) {
} }
} }
func (p *StackParamType) UnmarshalJSON(data []byte) (err error) { func (t *StackParamType) UnmarshalJSON(data []byte) (err error) {
var ( var (
s = string(data) s = string(data)
l = len(s) l = len(s)
) )
if l < 2 || s[0] != '"' || s[l-1] != '"' { if l < 2 || s[0] != '"' || s[l-1] != '"' {
*p = Unknown *t = Unknown
return errors.Errorf("invalid type: %s", s) return errors.Errorf("invalid type: %s", s)
} }
*p, err = StackParamTypeFromString(s[1 : l-1]) *t, err = StackParamTypeFromString(s[1 : l-1])
return return
} }

View file

@ -77,8 +77,8 @@ func GetInvocationScript(tx *transaction.Transaction, wif wallet.WIF) ([]byte, e
if err = tx.EncodeBinary(buf); err != nil { if err = tx.EncodeBinary(buf); err != nil {
return nil, errs.Wrap(err, "Failed to encode transaction to binary") return nil, errs.Wrap(err, "Failed to encode transaction to binary")
} }
bytes := buf.Bytes() data := buf.Bytes()
signature, err = wif.PrivateKey.Sign(bytes[:(len(bytes) - 1)]) signature, err = wif.PrivateKey.Sign(data[:(len(data) - 1)])
if err != nil { if err != nil {
return nil, errs.Wrap(err, "Failed ti sign transaction with private key") return nil, errs.Wrap(err, "Failed ti sign transaction with private key")
} }

View file

@ -39,4 +39,3 @@ type (
GetBalance(address string) ([]*Unspent, error) GetBalance(address string) ([]*Unspent, error)
} }
) )

View file

@ -14,7 +14,7 @@ type InvokeResult struct {
State string `json:"state"` State string `json:"state"`
GasConsumed string `json:"gas_consumed"` GasConsumed string `json:"gas_consumed"`
Script string `json:"script"` Script string `json:"script"`
Stack []*StackParam Stack []StackParam
} }
// AccountStateResponse holds the getaccountstate response. // AccountStateResponse holds the getaccountstate response.

View file

@ -22,13 +22,21 @@ func CreateMultiSigRedeemScript(m int, publicKeys crypto.PublicKeys) ([]byte, er
} }
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
vm.EmitInt(buf, int64(m)) if err := vm.EmitInt(buf, int64(m)); err != nil {
return nil, err
}
sort.Sort(publicKeys) sort.Sort(publicKeys)
for _, pubKey := range publicKeys { for _, pubKey := range publicKeys {
vm.EmitBytes(buf, pubKey.Bytes()) if err := vm.EmitBytes(buf, pubKey.Bytes()); err != nil {
return nil, err
}
}
if err := vm.EmitInt(buf, int64(len(publicKeys))); err != nil {
return nil, err
}
if err := vm.EmitOpcode(buf, vm.Ocheckmultisig); err != nil {
return nil, err
} }
vm.EmitInt(buf, int64(len(publicKeys)))
vm.EmitOpcode(buf, vm.Ocheckmultisig)
return buf.Bytes(), nil return buf.Bytes(), nil
} }

View file

@ -33,9 +33,7 @@ func Uint160DecodeBytes(b []byte) (u Uint160, err error) {
if len(b) != uint160Size { if len(b) != uint160Size {
return u, fmt.Errorf("expected byte size of %d got %d", uint160Size, len(b)) return u, fmt.Errorf("expected byte size of %d got %d", uint160Size, len(b))
} }
for i := 0; i < uint160Size; i++ { copy(u[:], b)
u[i] = b[i]
}
return return
} }

View file

@ -30,9 +30,7 @@ func Uint256DecodeBytes(b []byte) (u Uint256, err error) {
if len(b) != uint256Size { if len(b) != uint256Size {
return u, fmt.Errorf("expected []byte of size %d got %d", uint256Size, len(b)) return u, fmt.Errorf("expected []byte of size %d got %d", uint256Size, len(b))
} }
for i := 0; i < uint256Size; i++ { copy(u[:], b)
u[i] = b[i]
}
return u, nil return u, nil
} }

View file

@ -188,7 +188,7 @@ func (c *VMCLI) Run() error {
if len(input) != 0 { if len(input) != 0 {
parts := strings.Split(input, " ") parts := strings.Split(input, " ")
cmd := parts[0] cmd := parts[0]
args := []string{} var args []string
if len(parts) > 1 { if len(parts) > 1 {
args = parts[1:] args = parts[1:]
} }

View file

@ -38,7 +38,7 @@ func emitInt(w *bytes.Buffer, i int64) error {
return emitOpcode(w, vm.Opushf) return emitOpcode(w, vm.Opushf)
} }
if i > 0 && i < 16 { if i > 0 && i < 16 {
val := vm.Opcode((int(vm.Opush1) - 1 + int(i))) val := vm.Opcode(int(vm.Opush1) - 1 + int(i))
return emitOpcode(w, val) return emitOpcode(w, val)
} }
@ -83,7 +83,7 @@ func emitSyscall(w *bytes.Buffer, api string) error {
} }
buf := make([]byte, len(api)+1) buf := make([]byte, len(api)+1)
buf[0] = byte(len(api)) buf[0] = byte(len(api))
copy(buf[1:len(buf)], []byte(api)) copy(buf[1:], []byte(api))
return emit(w, vm.Osyscall, buf) return emit(w, vm.Osyscall, buf)
} }

View file

@ -41,7 +41,7 @@ func EmitInt(w *bytes.Buffer, i int64) error {
return EmitOpcode(w, Opushf) return EmitOpcode(w, Opushf)
} }
if i > 0 && i < 16 { if i > 0 && i < 16 {
val := Opcode((int(Opush1) - 1 + int(i))) val := Opcode(int(Opush1) - 1 + int(i))
return EmitOpcode(w, val) return EmitOpcode(w, val)
} }

View file

@ -9,7 +9,7 @@ type Opcode byte
const ( const (
// Constants // Constants
Opush0 Opcode = 0x00 // An empty array of bytes is pushed onto the stack. Opush0 Opcode = 0x00 // An empty array of bytes is pushed onto the stack.
Opushf Opcode = Opush0 Opushf = Opush0
Opushbytes1 Opcode = 0x01 // 0x01-0x4B The next opcode bytes is data to be pushed onto the stack Opushbytes1 Opcode = 0x01 // 0x01-0x4B The next opcode bytes is data to be pushed onto the stack
Opushbytes75 Opcode = 0x4B Opushbytes75 Opcode = 0x4B
Opushdata1 Opcode = 0x4C // The next byte contains the number of bytes to be pushed onto the stack. Opushdata1 Opcode = 0x4C // The next byte contains the number of bytes to be pushed onto the stack.
@ -17,7 +17,7 @@ const (
Opushdata4 Opcode = 0x4E // The next four bytes contain the number of bytes to be pushed onto the stack. Opushdata4 Opcode = 0x4E // The next four bytes contain the number of bytes to be pushed onto the stack.
Opushm1 Opcode = 0x4F // The number -1 is pushed onto the stack. Opushm1 Opcode = 0x4F // The number -1 is pushed onto the stack.
Opush1 Opcode = 0x51 Opush1 Opcode = 0x51
Opusht Opcode = Opush1 Opusht = Opush1
Opush2 Opcode = 0x52 // The number 2 is pushed onto the stack. Opush2 Opcode = 0x52 // The number 2 is pushed onto the stack.
Opush3 Opcode = 0x53 // The number 3 is pushed onto the stack. Opush3 Opcode = 0x53 // The number 3 is pushed onto the stack.
Opush4 Opcode = 0x54 // The number 4 is pushed onto the stack. Opush4 Opcode = 0x54 // The number 4 is pushed onto the stack.

View file

@ -60,7 +60,7 @@ func TestPushBytes1to75(t *testing.T) {
} }
func TestPushm1to16(t *testing.T) { func TestPushm1to16(t *testing.T) {
prog := []byte{} var prog []byte
for i := int(Opushm1); i <= int(Opush16); i++ { for i := int(Opushm1); i <= int(Opush16); i++ {
if i == 80 { if i == 80 {
continue // opcode layout we got here. continue // opcode layout we got here.

View file

@ -107,4 +107,3 @@ func (wif WIF) GetVerificationScript() ([]byte, error) {
vScript = append(vScript, checksig) vScript = append(vScript, checksig)
return vScript, nil return vScript, nil
} }