[NOD-294] Fix golint in deploy.sh and fix all lint warnings (#380)

* [NOD-294] Fix golint in deploy.sh and fixed all lint errors

* [NOD-294] Fix typos in comments

* [NOD-294] Convert VirtualForTest into alias of *virtualBlock

* [NOD-294] Fixed some more typos in comments
This commit is contained in:
Svarog 2019-08-27 12:00:23 +03:00 committed by Ori Newman
parent c72b914050
commit 480b2ca07c
20 changed files with 60 additions and 28 deletions

View File

@ -135,15 +135,18 @@ func createTxForTest(numInputs uint32, numOutputs uint32, outputValue uint64, su
return wire.NewNativeMsgTx(wire.TxVersion, txIns, txOuts) return wire.NewNativeMsgTx(wire.TxVersion, txIns, txOuts)
} }
// VirtualForTest is an exported version for virtualBlock, so that it can be returned by exported test_util methods
type VirtualForTest *virtualBlock
// SetVirtualForTest replaces the dag's virtual block. This function is used for test purposes only // SetVirtualForTest replaces the dag's virtual block. This function is used for test purposes only
func SetVirtualForTest(dag *BlockDAG, virtual *virtualBlock) *virtualBlock { func SetVirtualForTest(dag *BlockDAG, virtual VirtualForTest) VirtualForTest {
oldVirtual := dag.virtual oldVirtual := dag.virtual
dag.virtual = virtual dag.virtual = virtual
return oldVirtual return VirtualForTest(oldVirtual)
} }
// GetVirtualFromParentsForTest generates a virtual block with the given parents. // GetVirtualFromParentsForTest generates a virtual block with the given parents.
func GetVirtualFromParentsForTest(dag *BlockDAG, parentHashes []*daghash.Hash) (*virtualBlock, error) { func GetVirtualFromParentsForTest(dag *BlockDAG, parentHashes []*daghash.Hash) (VirtualForTest, error) {
parents := newSet() parents := newSet()
for _, hash := range parentHashes { for _, hash := range parentHashes {
parent := dag.index.LookupNode(hash) parent := dag.index.LookupNode(hash)
@ -173,5 +176,5 @@ func GetVirtualFromParentsForTest(dag *BlockDAG, parentHashes []*daghash.Hash) (
} }
virtual.utxoSet = diffUTXO.base virtual.utxoSet = diffUTXO.base
return virtual, nil return VirtualForTest(virtual), nil
} }

View File

@ -461,7 +461,7 @@ func TestUnmarshalCmdErrors(t *testing.T) {
{ {
name: "unregistered type", name: "unregistered type",
request: btcjson.Request{ request: btcjson.Request{
JsonRPC: "1.0", JSONRPC: "1.0",
Method: "bogusMethod", Method: "bogusMethod",
Params: nil, Params: nil,
ID: nil, ID: nil,
@ -471,7 +471,7 @@ func TestUnmarshalCmdErrors(t *testing.T) {
{ {
name: "incorrect number of params", name: "incorrect number of params",
request: btcjson.Request{ request: btcjson.Request{
JsonRPC: "1.0", JSONRPC: "1.0",
Method: "getBlockCount", Method: "getBlockCount",
Params: []json.RawMessage{[]byte(`"bogusparam"`)}, Params: []json.RawMessage{[]byte(`"bogusparam"`)},
ID: nil, ID: nil,
@ -481,7 +481,7 @@ func TestUnmarshalCmdErrors(t *testing.T) {
{ {
name: "invalid type for a parameter", name: "invalid type for a parameter",
request: btcjson.Request{ request: btcjson.Request{
JsonRPC: "1.0", JSONRPC: "1.0",
Method: "getBlock", Method: "getBlock",
Params: []json.RawMessage{[]byte("1")}, Params: []json.RawMessage{[]byte("1")},
ID: nil, ID: nil,
@ -491,7 +491,7 @@ func TestUnmarshalCmdErrors(t *testing.T) {
{ {
name: "invalid JSON for a parameter", name: "invalid JSON for a parameter",
request: btcjson.Request{ request: btcjson.Request{
JsonRPC: "1.0", JSONRPC: "1.0",
Method: "getBlock", Method: "getBlock",
Params: []json.RawMessage{[]byte(`"1`)}, Params: []json.RawMessage{[]byte(`"1`)},
ID: nil, ID: nil,

View File

@ -67,7 +67,7 @@ func IsValidIDType(id interface{}) bool {
// requests, however this struct it being exported in case the caller wants to // requests, however this struct it being exported in case the caller wants to
// construct raw requests for some reason. // construct raw requests for some reason.
type Request struct { type Request struct {
JsonRPC string `json:"jsonrpc"` JSONRPC string `json:"jsonrpc"`
Method string `json:"method"` Method string `json:"method"`
Params []json.RawMessage `json:"params"` Params []json.RawMessage `json:"params"`
ID interface{} `json:"id"` ID interface{} `json:"id"`
@ -98,7 +98,7 @@ func NewRequest(id interface{}, method string, params []interface{}) (*Request,
} }
return &Request{ return &Request{
JsonRPC: "1.0", JSONRPC: "1.0",
ID: id, ID: id,
Method: method, Method: method,
Params: rawParams, Params: rawParams,

View File

@ -2,7 +2,6 @@ package main
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log" "log"
@ -48,7 +47,7 @@ func (s *server) start() error {
rpcClient, err := rpcclient.New(s.rpcConnConfig, nil) rpcClient, err := rpcclient.New(s.rpcConnConfig, nil)
if err != nil { if err != nil {
return errors.New(fmt.Sprintf("failed to create RPC client: %s", err)) return fmt.Errorf("failed to create RPC client: %s", err)
} }
s.rpcClient = rpcClient s.rpcClient = rpcClient
@ -103,18 +102,18 @@ func (s *server) forwardRequest(request *http.Request) ([]byte, error) {
requestBody, err := ioutil.ReadAll(request.Body) requestBody, err := ioutil.ReadAll(request.Body)
if err != nil { if err != nil {
return nil, errors.New(fmt.Sprintf("failed to read request body: %s", err)) return nil, fmt.Errorf("failed to read request body: %s", err)
} }
var jsonRPCParams []json.RawMessage var jsonRPCParams []json.RawMessage
err = json.Unmarshal(requestBody, &jsonRPCParams) err = json.Unmarshal(requestBody, &jsonRPCParams)
if err != nil { if err != nil {
return nil, errors.New(fmt.Sprintf("failed to parse params: %s", err)) return nil, fmt.Errorf("failed to parse params: %s", err)
} }
response, err := s.rpcClient.RawRequest(jsonRPCMethod, jsonRPCParams) response, err := s.rpcClient.RawRequest(jsonRPCMethod, jsonRPCParams)
if err != nil { if err != nil {
return nil, errors.New(fmt.Sprintf("request to rpc server failed: %s", err)) return nil, fmt.Errorf("request to rpc server failed: %s", err)
} }
return response, nil return response, nil

View File

@ -2,6 +2,7 @@ package main
import ( import (
"fmt" "fmt"
"github.com/daglabs/btcd/btcec" "github.com/daglabs/btcd/btcec"
"github.com/daglabs/btcd/dagconfig" "github.com/daglabs/btcd/dagconfig"
"github.com/daglabs/btcd/signal" "github.com/daglabs/btcd/signal"
@ -11,7 +12,7 @@ import (
) )
var ( var (
activeNetParams *dagconfig.Params = &dagconfig.DevNetParams activeNetParams = &dagconfig.DevNetParams
p2pkhAddress util.Address p2pkhAddress util.Address
secondaryAddress util.Address secondaryAddress util.Address
privateKey *btcec.PrivateKey privateKey *btcec.PrivateKey

View File

@ -18,6 +18,7 @@ import (
"github.com/miekg/dns" "github.com/miekg/dns"
) )
// Node repesents a node in the DAGCoin network
type Node struct { type Node struct {
Addr *wire.NetAddress Addr *wire.NetAddress
Services wire.ServiceFlag Services wire.ServiceFlag
@ -27,6 +28,8 @@ type Node struct {
SubnetworkID *subnetworkid.SubnetworkID SubnetworkID *subnetworkid.SubnetworkID
} }
// Manager is dnsseeder's main worker-type, storing all information required
// for operation
type Manager struct { type Manager struct {
mtx sync.RWMutex mtx sync.RWMutex
@ -118,6 +121,7 @@ func isRoutable(addr net.IP) bool {
return true return true
} }
// NewManager constructs and returns a new dnsseeder manager, with the provided dataDir
func NewManager(dataDir string) (*Manager, error) { func NewManager(dataDir string) (*Manager, error) {
amgr := Manager{ amgr := Manager{
nodes: make(map[string]*Node), nodes: make(map[string]*Node),
@ -142,6 +146,8 @@ func NewManager(dataDir string) (*Manager, error) {
return &amgr, nil return &amgr, nil
} }
// AddAddresses adds an address to this dnsseeder manager, and returns the number of
// address currently held
func (m *Manager) AddAddresses(addrs []*wire.NetAddress) int { func (m *Manager) AddAddresses(addrs []*wire.NetAddress) int {
var count int var count int
@ -245,6 +251,7 @@ func (m *Manager) GoodAddresses(qtype uint16, services wire.ServiceFlag, include
return addrs return addrs
} }
// Attempt updates the last connection attempt for the specified ip address to now
func (m *Manager) Attempt(ip net.IP) { func (m *Manager) Attempt(ip net.IP) {
m.mtx.Lock() m.mtx.Lock()
node, exists := m.nodes[ip.String()] node, exists := m.nodes[ip.String()]
@ -254,6 +261,7 @@ func (m *Manager) Attempt(ip net.IP) {
m.mtx.Unlock() m.mtx.Unlock()
} }
// Good updates the last successful connection attempt for the specified ip address to now
func (m *Manager) Good(ip net.IP, services wire.ServiceFlag, subnetworkid *subnetworkid.SubnetworkID) { func (m *Manager) Good(ip net.IP, services wire.ServiceFlag, subnetworkid *subnetworkid.SubnetworkID) {
m.mtx.Lock() m.mtx.Lock()
node, exists := m.nodes[ip.String()] node, exists := m.nodes[ip.String()]

View File

@ -23,9 +23,9 @@ RUN go mod download
COPY . . COPY . .
RUN TEST_DIRS=`go list -f {{.Dir}} ./... | grep -v /vendor/` GOFMT_RESULT=`gofmt -l $TEST_DIRS`; echo $GOFMT_RESULT; test -z "$GOFMT_RESULT" RUN GOFMT_RESULT=`go fmt ./...`; echo $GOFMT_RESULT; test -z "$GOFMT_RESULT"
RUN go vet ./... RUN go vet ./...
RUN TEST_DIRS=`go list -f {{.Dir}} ./... | grep -v /vendor/` golint -set_exit_status $TEST_DIRS RUN golint -set_exit_status ./...
# RUN aligncheck ./... # RUN aligncheck ./...
# RUN structcheck -e ./... # RUN structcheck -e ./...
# RUN varcheck -e ./... # RUN varcheck -e ./...

View File

@ -3,7 +3,7 @@
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
/* /*
Package btclog defines an interface and default implementation for subsystem Package logs defines an interface and default implementation for subsystem
logging. logging.
Log level verbosity may be modified at runtime for each individual subsystem Log level verbosity may be modified at runtime for each individual subsystem

View File

@ -35,7 +35,6 @@ package logs
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"github.com/jrick/logrotate/rotator"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -43,6 +42,8 @@ import (
"sync" "sync"
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/jrick/logrotate/rotator"
) )
// defaultFlags specifies changes to the default logger behavior. It is set // defaultFlags specifies changes to the default logger behavior. It is set
@ -269,11 +270,11 @@ func (b *Backend) AddLogFile(logFile string, logLevel Level) error {
logDir, _ := filepath.Split(logFile) logDir, _ := filepath.Split(logFile)
err := os.MkdirAll(logDir, 0700) err := os.MkdirAll(logDir, 0700)
if err != nil { if err != nil {
return fmt.Errorf("failed to create log directory: %s\n", err) return fmt.Errorf("failed to create log directory: %s", err)
} }
r, err := rotator.New(logFile, 10*1024, false, 3) r, err := rotator.New(logFile, 10*1024, false, 3)
if err != nil { if err != nil {
return fmt.Errorf("failed to create file rotator: %s\n", err) return fmt.Errorf("failed to create file rotator: %s", err)
} }
b.rotators = append(b.rotators, &backendLogRotator{ b.rotators = append(b.rotators, &backendLogRotator{
Rotator: r, Rotator: r,
@ -342,6 +343,7 @@ func (b *Backend) write(lvl Level, bytesToWrite []byte) {
b.mu.Unlock() b.mu.Unlock()
} }
// Close finalizes all log rotators for this backend
func (b *Backend) Close() { func (b *Backend) Close() {
for _, r := range b.rotators { for _, r := range b.rotators {
r.Close() r.Close()

View File

@ -122,6 +122,7 @@ func GenerateDeterministicExtraNonceForTest() uint64 {
return extraNonceForTest return extraNonceForTest
} }
// OpTrueAddress returns an address pointing to a P2SH anyone-can-spend script
func OpTrueAddress(prefix util.Bech32Prefix) (util.Address, error) { func OpTrueAddress(prefix util.Bech32Prefix) (util.Address, error) {
return util.NewAddressScriptHash(blockdag.OpTrueScript, prefix) return util.NewAddressScriptHash(blockdag.OpTrueScript, prefix)
} }

View File

@ -177,6 +177,10 @@ type SyncManager struct {
nextCheckpoint *dagconfig.Checkpoint nextCheckpoint *dagconfig.Checkpoint
} }
// PushGetBlockInvsOrHeaders sends a getblockinvs or getheaders message according to checkpoint status
// for the provided start hash.
//
// This function is safe for concurrent access.
func (sm *SyncManager) PushGetBlockInvsOrHeaders(peer *peerpkg.Peer, startHash *daghash.Hash) error { func (sm *SyncManager) PushGetBlockInvsOrHeaders(peer *peerpkg.Peer, startHash *daghash.Hash) error {
// When the current height is less than a known checkpoint we // When the current height is less than a known checkpoint we
// can use block headers to learn about which blocks comprise // can use block headers to learn about which blocks comprise

View File

@ -860,6 +860,10 @@ func (p *Peer) PushAddrMsg(addresses []*wire.NetAddress, subnetworkID *subnetwor
return msg.AddrList, nil return msg.AddrList, nil
} }
// PushGetBlockLocatorMsg sends a getlocator message for the provided start
// and stop hash.
//
// This function is safe for concurrent access.
func (p *Peer) PushGetBlockLocatorMsg(startHash, stopHash *daghash.Hash) { func (p *Peer) PushGetBlockLocatorMsg(startHash, stopHash *daghash.Hash) {
msg := wire.NewMsgGetBlockLocator(startHash, stopHash) msg := wire.NewMsgGetBlockLocator(startHash, stopHash)
p.QueueMessage(msg, nil) p.QueueMessage(msg, nil)

View File

@ -561,6 +561,8 @@ func (c *Client) GetRawMempoolVerbose() (map[string]btcjson.GetRawMempoolVerbose
// GetSubnetworkAsync RPC invocation (or an applicable error). // GetSubnetworkAsync RPC invocation (or an applicable error).
type FutureGetSubnetworkResult chan *response type FutureGetSubnetworkResult chan *response
// Receive waits for the response promised by the future and returns information
// regarding the requested subnetwork
func (r FutureGetSubnetworkResult) Receive() (*btcjson.GetSubnetworkResult, error) { func (r FutureGetSubnetworkResult) Receive() (*btcjson.GetSubnetworkResult, error) {
res, err := receiveFuture(r) res, err := receiveFuture(r)
if err != nil { if err != nil {

View File

@ -44,7 +44,7 @@ func (c *Client) RawRequestAsync(method string, params []json.RawMessage) Future
// than custom commands. // than custom commands.
id := c.NextID() id := c.NextID()
rawRequest := &btcjson.Request{ rawRequest := &btcjson.Request{
JsonRPC: "1.0", JSONRPC: "1.0",
ID: id, ID: id,
Method: method, Method: method,
Params: params, Params: params,

View File

@ -3995,7 +3995,7 @@ func (s *Server) jsonRPCRead(w http.ResponseWriter, r *http.Request, isAdmin boo
// //
// RPC quirks can be enabled by the user to avoid compatibility issues // RPC quirks can be enabled by the user to avoid compatibility issues
// with software relying on Core's behavior. // with software relying on Core's behavior.
if request.ID == nil && !(config.MainConfig().RPCQuirks && request.JsonRPC == "") { if request.ID == nil && !(config.MainConfig().RPCQuirks && request.JSONRPC == "") {
return return
} }

View File

@ -997,7 +997,7 @@ out:
// //
// RPC quirks can be enabled by the user to avoid compatibility issues // RPC quirks can be enabled by the user to avoid compatibility issues
// with software relying on Core's behavior. // with software relying on Core's behavior.
if request.ID == nil && !(config.MainConfig().RPCQuirks && request.JsonRPC == "") { if request.ID == nil && !(config.MainConfig().RPCQuirks && request.JSONRPC == "") {
if !c.authenticated { if !c.authenticated {
break out break out
} }

View File

@ -164,6 +164,7 @@ type AddressPubKeyHash struct {
hash [ripemd160.Size]byte hash [ripemd160.Size]byte
} }
// NewAddressPubKeyHashFromPublicKey returns a new AddressPubKeyHash from given public key
func NewAddressPubKeyHashFromPublicKey(publicKey []byte, prefix Bech32Prefix) (*AddressPubKeyHash, error) { func NewAddressPubKeyHashFromPublicKey(publicKey []byte, prefix Bech32Prefix) (*AddressPubKeyHash, error) {
pkHash := Hash160(publicKey) pkHash := Hash160(publicKey)
return newAddressPubKeyHash(prefix, pkHash) return newAddressPubKeyHash(prefix, pkHash)

View File

@ -31,6 +31,7 @@ type PriorityMutex struct {
lowPriorityMutex sync.Mutex lowPriorityMutex sync.Mutex
} }
// NewPriorityMutex returns a new priority mutex
func NewPriorityMutex() *PriorityMutex { func NewPriorityMutex() *PriorityMutex {
lock := PriorityMutex{ lock := PriorityMutex{
highPriorityWaiting: newWaitGroup(), highPriorityWaiting: newWaitGroup(),
@ -70,7 +71,7 @@ func (mtx *PriorityMutex) HighPriorityReadLock() {
mtx.dataMutex.RLock() mtx.dataMutex.RLock()
} }
// HighPriorityWriteUnlock unlocks the high-priority read // HighPriorityReadUnlock unlocks the high-priority read
// lock // lock
func (mtx *PriorityMutex) HighPriorityReadUnlock() { func (mtx *PriorityMutex) HighPriorityReadUnlock() {
mtx.highPriorityWaiting.done() mtx.highPriorityWaiting.done()

View File

@ -21,7 +21,7 @@ import (
// backing array multiple times. // backing array multiple times.
const defaultTransactionAlloc = 2048 const defaultTransactionAlloc = 2048
// maxMassPerBlock is the maximum total transaction mass a block may contain. // MaxMassPerBlock is the maximum total transaction mass a block may contain.
const MaxMassPerBlock = 10000000 const MaxMassPerBlock = 10000000
// maxTxPerBlock is the maximum number of transactions that could // maxTxPerBlock is the maximum number of transactions that could

View File

@ -1,10 +1,16 @@
package wire package wire
import ( import (
"github.com/daglabs/btcd/util/daghash"
"io" "io"
"github.com/daglabs/btcd/util/daghash"
) )
// MsgGetBlockLocator implements the Message interface and represents a bitcoin
// getlocator message. It is used to request a block locator between start and stop hash.
// The locator is returned via a locator message (MsgBlockLocator).
//
// This message has no payload.
type MsgGetBlockLocator struct { type MsgGetBlockLocator struct {
StartHash *daghash.Hash StartHash *daghash.Hash
StopHash *daghash.Hash StopHash *daghash.Hash