[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(),
}
ctl.Run(os.Args)
if err := ctl.Run(os.Args); err != nil {
panic(err)
}
}

View file

@ -12,8 +12,8 @@ import (
)
var (
errNoPath = errors.New("target path where the wallet should be stored is mandatory and should be passed using (--path, -p) flags")
errPhraseMismatch = errors.New("the entered pass-phrases do not match. Maybe you have misspelled them")
errNoPath = errors.New("target path where the wallet should be stored is mandatory and should be passed using (--path, -p) flags")
errPhraseMismatch = errors.New("the entered pass-phrases do not match. Maybe you have misspelled them")
)
// NewCommand creates a new Wallet command.

View file

@ -8,8 +8,6 @@ import (
"time"
"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/transaction"
"github.com/CityOfZion/neo-go/pkg/util"
@ -104,7 +102,9 @@ func (bc *Blockchain) init() error {
ver, err := storage.Version(bc.Store)
if err != nil {
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)
}
if ver != version {
@ -284,11 +284,17 @@ func (bc *Blockchain) persistBlock(block *Block) error {
assets = make(Assets)
)
storeAsBlock(batch, block, 0)
if err := storeAsBlock(batch, block, 0); err != nil {
return err
}
storeAsCurrentBlock(batch, block)
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))
// Process TX outputs.
@ -471,9 +477,9 @@ func (bc *Blockchain) GetBlock(hash util.Uint256) (*Block, error) {
return nil, err
}
// TODO: persist TX first before we can handle this logic.
//if len(block.Transactions) == 0 {
// return nil, fmt.Errorf("block has no TX")
//}
// if len(block.Transactions) == 0 {
// return nil, fmt.Errorf("block has no TX")
// }
return block, nil
}

View file

@ -21,7 +21,10 @@ func (h *Header) DecodeBinary(r io.Reader) error {
}
var padding uint8
binary.Read(r, binary.LittleEndian, &padding)
if err := binary.Read(r, binary.LittleEndian, &padding); err != nil {
return err
}
if padding != 0 {
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 {
b := batch.(*MemoryBatch)
for k, v := range b.m {
s.Put(*k, v)
if err := s.Put(*k, v); err != nil {
return err
}
}
return nil
}

View file

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

View file

@ -10,7 +10,7 @@ type ContractTX struct{}
func NewContractTX() *Transaction {
return &Transaction{
Type: ContractType,
Type: ContractType,
}
}

View file

@ -2,7 +2,7 @@ package transaction
import "io"
//TXer is interface that can act as the underlying data of
// TXer is interface that can act as the underlying data of
// a transaction.
type TXer interface {
DecodeBinary(io.Reader) error

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
}

View file

@ -5,6 +5,8 @@ import (
"crypto/sha256"
"fmt"
"math/big"
"github.com/pkg/errors"
)
const prefix rune = '1'
@ -54,7 +56,7 @@ func Base58Decode(s string) ([]byte, error) {
}
out := n.Bytes()
buf := make([]byte, (zero + len(out)))
buf := make([]byte, zero+len(out))
copy(buf[zero:], out[:])
return buf, nil
@ -94,7 +96,7 @@ func Base58CheckDecode(s string) (b []byte, err error) {
}
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()
@ -106,7 +108,7 @@ func Base58CheckDecode(s string) (b []byte, err error) {
hash = sha.Sum(nil)
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.

View file

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

View file

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

View file

@ -4,6 +4,6 @@ import "io"
// Payload is anything that can be binary encoded/decoded.
type Payload interface {
EncodeBinary(io.Writer) error
DecodeBinary(io.Reader) error
EncodeBinary(io.Writer) error
DecodeBinary(io.Reader) error
}

View file

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

View file

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

View file

@ -28,7 +28,9 @@ func TestSendVersion(t *testing.T) {
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.

View file

@ -128,7 +128,7 @@ func (c *Client) performRequest(method string, p params, v interface{}) error {
defer resp.Body.Close()
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)

View file

@ -29,12 +29,7 @@ func (s NeoScanServer) GetBalance(address string) ([]*Unspent, error) {
return nil, errs.Wrap(err, "Failed to perform HTTP request")
}
defer func() error {
if err := res.Body.Close(); err != nil {
return err
}
return nil
}()
defer res.Body.Close()
if err = json.NewDecoder(res.Body).Decode(&balance); err != nil {
return nil, errs.Wrap(err, "Failed to decode HTTP response")
@ -78,7 +73,7 @@ func (s NeoScanServer) CalculateInputs(address string, assetIdUint util.Uint256,
num++
}
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)

View file

@ -6,6 +6,7 @@ import (
"io"
"net/http"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
@ -47,11 +48,11 @@ func (r *Request) DecodeData(data io.ReadCloser) error {
err := json.NewDecoder(data).Decode(r)
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 {
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
@ -64,7 +65,7 @@ func (r *Request) Params() (*Params, error) {
err := json.Unmarshal(r.RawParams, &params)
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

View file

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

View file

@ -9,9 +9,8 @@ import (
"strconv"
"testing"
"github.com/CityOfZion/neo-go/pkg/core"
"github.com/CityOfZion/neo-go/config"
"github.com/CityOfZion/neo-go/pkg/core"
"github.com/CityOfZion/neo-go/pkg/network"
"github.com/stretchr/testify/assert"
)
@ -25,12 +24,12 @@ func TestHandler(t *testing.T) {
cfg, err := config.Load(configPath, net)
if err != nil {
t.Errorf("could not load configuration file")
t.Fatal("could not create levelDB chain", err)
}
chain, err := core.NewBlockchainLevelDB(cfg)
if err != nil {
t.Errorf("could not create levelDB chain")
t.Fatal("could not create levelDB chain", err)
}
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 (
s = string(data)
l = len(s)
)
if l < 2 || s[0] != '"' || s[l-1] != '"' {
*p = Unknown
*t = Unknown
return errors.Errorf("invalid type: %s", s)
}
*p, err = StackParamTypeFromString(s[1 : l-1])
*t, err = StackParamTypeFromString(s[1 : l-1])
return
}
@ -149,7 +149,7 @@ func (p *StackParam) UnmarshalJSON(data []byte) (err error) {
}
p.Value = i
case Array:
//https://github.com/neo-project/neo/blob/3d59ecca5a8deb057bdad94b3028a6d5e25ac088/neo/Network/RPC/RpcServer.cs#L67
// https://github.com/neo-project/neo/blob/3d59ecca5a8deb057bdad94b3028a6d5e25ac088/neo/Network/RPC/RpcServer.cs#L67
var rs []StackParam
if err = json.Unmarshal(r.Value, &rs); err != nil {
return

View file

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

View file

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

View file

@ -14,7 +14,7 @@ type InvokeResult struct {
State string `json:"state"`
GasConsumed string `json:"gas_consumed"`
Script string `json:"script"`
Stack []*StackParam
Stack []StackParam
}
// AccountStateResponse holds the getaccountstate response.
@ -80,37 +80,37 @@ type SendToAddressResponse struct {
type GetRawTxResponse struct {
responseHeader
Error *Error `json:"error"`
Result *RawTxResponse `json: "result"`
Result *RawTxResponse `json:"result"`
}
type RawTxResponse struct {
TxResponse
BlockHash string `json: "blockhash"`
Confirmations uint `json: "confirmations"`
BlockTime uint `json: "blocktime"`
BlockHash string `json:"blockhash"`
Confirmations uint `json:"confirmations"`
BlockTime uint `json:"blocktime"`
}
type TxResponse struct {
TxID string `json: "txid"`
Size int `json: "size"`
Type string `json: "type"` // todo: convert to TransactionType
Version int `json: "version"`
Attributes []transaction.Attribute `json: "attributes"`
Vins []Vin `json: "vin"`
Vouts []Vout `json: "vout"`
SysFee int `json: "sys_fee"`
NetFee int `json: "net_fee"`
Scripts []transaction.Witness `json: "scripts"`
TxID string `json:"txid"`
Size int `json:"size"`
Type string `json:"type"` // todo: convert to TransactionType
Version int `json:"version"`
Attributes []transaction.Attribute `json:"attributes"`
Vins []Vin `json:"vin"`
Vouts []Vout `json:"vout"`
SysFee int `json:"sys_fee"`
NetFee int `json:"net_fee"`
Scripts []transaction.Witness `json:"scripts"`
}
type Vin struct {
TxId string `json: "txid"`
Vout int `json: "vout"`
TxId string `json:"txid"`
Vout int `json:"vout"`
}
type Vout struct {
N int `json: "n"`
Asset string `json: "asset"`
Value int `json: "value"`
Address string `json: "address"`
N int `json:"n"`
Asset string `json:"asset"`
Value int `json:"value"`
Address string `json:"address"`
}

View file

@ -22,13 +22,21 @@ func CreateMultiSigRedeemScript(m int, publicKeys crypto.PublicKeys) ([]byte, er
}
buf := new(bytes.Buffer)
vm.EmitInt(buf, int64(m))
if err := vm.EmitInt(buf, int64(m)); err != nil {
return nil, err
}
sort.Sort(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
}

View file

@ -27,32 +27,32 @@ type Parameter struct {
}
func (pt ParamType) String() string {
switch pt {
case SignatureType:
return "Signature"
case BoolType:
return "Boolean"
case IntegerType:
return "Integer"
case Hash160Type:
return "Hash160"
case Hash256Type:
return "Hash256"
case ByteArrayType:
return "ByteArray"
case PublicKeyType:
return "PublicKey"
case StringType:
return "String"
case ArrayType:
return "Array"
default:
return ""
}
switch pt {
case SignatureType:
return "Signature"
case BoolType:
return "Boolean"
case IntegerType:
return "Integer"
case Hash160Type:
return "Hash160"
case Hash256Type:
return "Hash256"
case ByteArrayType:
return "ByteArray"
case PublicKeyType:
return "PublicKey"
case StringType:
return "String"
case ArrayType:
return "Array"
default:
return ""
}
}
func (pt ParamType) MarshalJSON() ([]byte, error) {
return []byte(`"` + pt.String() + `"`), nil
return []byte(`"` + pt.String() + `"`), nil
}
// NewParameter returns a Parameter with proper initialized Value

View file

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

View file

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

View file

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

View file

@ -38,7 +38,7 @@ func emitInt(w *bytes.Buffer, i int64) error {
return emitOpcode(w, vm.Opushf)
}
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)
}
@ -83,7 +83,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, vm.Osyscall, buf)
}

View file

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

View file

@ -9,7 +9,7 @@ type Opcode byte
const (
// Constants
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
Opushbytes75 Opcode = 0x4B
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.
Opushm1 Opcode = 0x4F // The number -1 is pushed onto the stack.
Opush1 Opcode = 0x51
Opusht Opcode = Opush1
Opusht = Opush1
Opush2 Opcode = 0x52 // The number 2 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.

View file

@ -696,8 +696,8 @@ func (v *VM) execute(ctx *Context, op Opcode) {
v.estack.PushVal(sha.Sum(nil))
case Ochecksig:
//pubkey := v.estack.Pop().Bytes()
//sig := v.estack.Pop().Bytes()
// pubkey := v.estack.Pop().Bytes()
// sig := v.estack.Pop().Bytes()
case Ocheckmultisig:

View file

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

View file

@ -1,6 +1,6 @@
package wallet
import(
import (
"testing"
)
@ -17,7 +17,7 @@ func TestNEP2Encrypt(t *testing.T) {
t.Fatal(err)
}
if want, have:= testCase.encryptedWif, encryptedWif; want != have {
if want, have := testCase.encryptedWif, encryptedWif; want != have {
t.Fatalf("expected %s got %s", want, have)
}
}
@ -42,7 +42,7 @@ func TestNEP2Decrypt(t *testing.T) {
}
wif, err := privKey.WIF()
if err != nil{
if err != nil {
t.Fatal(err)
}
if want, have := testCase.wif, wif; want != have {
@ -50,11 +50,11 @@ func TestNEP2Decrypt(t *testing.T) {
}
address, err := privKey.Address()
if err != nil{
if err != nil {
t.Fatal(err)
}
if want, have := testCase.address, address; want != have {
t.Fatalf("expected %s got %s", want, have)
}
}
}
}

View file

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