diff --git a/blockdag/test_utils.go b/blockdag/test_utils.go index 22fd1c9dd..44be44af7 100644 --- a/blockdag/test_utils.go +++ b/blockdag/test_utils.go @@ -135,15 +135,18 @@ func createTxForTest(numInputs uint32, numOutputs uint32, outputValue uint64, su 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 -func SetVirtualForTest(dag *BlockDAG, virtual *virtualBlock) *virtualBlock { +func SetVirtualForTest(dag *BlockDAG, virtual VirtualForTest) VirtualForTest { oldVirtual := dag.virtual dag.virtual = virtual - return oldVirtual + return VirtualForTest(oldVirtual) } // 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() for _, hash := range parentHashes { parent := dag.index.LookupNode(hash) @@ -173,5 +176,5 @@ func GetVirtualFromParentsForTest(dag *BlockDAG, parentHashes []*daghash.Hash) ( } virtual.utxoSet = diffUTXO.base - return virtual, nil + return VirtualForTest(virtual), nil } diff --git a/btcjson/cmdparse_test.go b/btcjson/cmdparse_test.go index c268fb270..6e0072440 100644 --- a/btcjson/cmdparse_test.go +++ b/btcjson/cmdparse_test.go @@ -461,7 +461,7 @@ func TestUnmarshalCmdErrors(t *testing.T) { { name: "unregistered type", request: btcjson.Request{ - JsonRPC: "1.0", + JSONRPC: "1.0", Method: "bogusMethod", Params: nil, ID: nil, @@ -471,7 +471,7 @@ func TestUnmarshalCmdErrors(t *testing.T) { { name: "incorrect number of params", request: btcjson.Request{ - JsonRPC: "1.0", + JSONRPC: "1.0", Method: "getBlockCount", Params: []json.RawMessage{[]byte(`"bogusparam"`)}, ID: nil, @@ -481,7 +481,7 @@ func TestUnmarshalCmdErrors(t *testing.T) { { name: "invalid type for a parameter", request: btcjson.Request{ - JsonRPC: "1.0", + JSONRPC: "1.0", Method: "getBlock", Params: []json.RawMessage{[]byte("1")}, ID: nil, @@ -491,7 +491,7 @@ func TestUnmarshalCmdErrors(t *testing.T) { { name: "invalid JSON for a parameter", request: btcjson.Request{ - JsonRPC: "1.0", + JSONRPC: "1.0", Method: "getBlock", Params: []json.RawMessage{[]byte(`"1`)}, ID: nil, diff --git a/btcjson/jsonrpc.go b/btcjson/jsonrpc.go index 670c81152..3365e3852 100644 --- a/btcjson/jsonrpc.go +++ b/btcjson/jsonrpc.go @@ -67,7 +67,7 @@ func IsValidIDType(id interface{}) bool { // requests, however this struct it being exported in case the caller wants to // construct raw requests for some reason. type Request struct { - JsonRPC string `json:"jsonrpc"` + JSONRPC string `json:"jsonrpc"` Method string `json:"method"` Params []json.RawMessage `json:"params"` ID interface{} `json:"id"` @@ -98,7 +98,7 @@ func NewRequest(id interface{}, method string, params []interface{}) (*Request, } return &Request{ - JsonRPC: "1.0", + JSONRPC: "1.0", ID: id, Method: method, Params: rawParams, diff --git a/cmd/jsonrpcifyer/server.go b/cmd/jsonrpcifyer/server.go index 4a5af8841..3c6abd503 100644 --- a/cmd/jsonrpcifyer/server.go +++ b/cmd/jsonrpcifyer/server.go @@ -2,7 +2,6 @@ package main import ( "encoding/json" - "errors" "fmt" "io/ioutil" "log" @@ -48,7 +47,7 @@ func (s *server) start() error { rpcClient, err := rpcclient.New(s.rpcConnConfig, 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 @@ -103,18 +102,18 @@ func (s *server) forwardRequest(request *http.Request) ([]byte, error) { requestBody, err := ioutil.ReadAll(request.Body) 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 err = json.Unmarshal(requestBody, &jsonRPCParams) 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) 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 diff --git a/cmd/txgen/main.go b/cmd/txgen/main.go index cf45a2c2b..0c39e0718 100644 --- a/cmd/txgen/main.go +++ b/cmd/txgen/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "github.com/daglabs/btcd/btcec" "github.com/daglabs/btcd/dagconfig" "github.com/daglabs/btcd/signal" @@ -11,7 +12,7 @@ import ( ) var ( - activeNetParams *dagconfig.Params = &dagconfig.DevNetParams + activeNetParams = &dagconfig.DevNetParams p2pkhAddress util.Address secondaryAddress util.Address privateKey *btcec.PrivateKey diff --git a/dnsseeder/manager.go b/dnsseeder/manager.go index 43b951e29..1320d9875 100644 --- a/dnsseeder/manager.go +++ b/dnsseeder/manager.go @@ -18,6 +18,7 @@ import ( "github.com/miekg/dns" ) +// Node repesents a node in the DAGCoin network type Node struct { Addr *wire.NetAddress Services wire.ServiceFlag @@ -27,6 +28,8 @@ type Node struct { SubnetworkID *subnetworkid.SubnetworkID } +// Manager is dnsseeder's main worker-type, storing all information required +// for operation type Manager struct { mtx sync.RWMutex @@ -118,6 +121,7 @@ func isRoutable(addr net.IP) bool { return true } +// NewManager constructs and returns a new dnsseeder manager, with the provided dataDir func NewManager(dataDir string) (*Manager, error) { amgr := Manager{ nodes: make(map[string]*Node), @@ -142,6 +146,8 @@ func NewManager(dataDir string) (*Manager, error) { 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 { var count int @@ -245,6 +251,7 @@ func (m *Manager) GoodAddresses(qtype uint16, services wire.ServiceFlag, include return addrs } +// Attempt updates the last connection attempt for the specified ip address to now func (m *Manager) Attempt(ip net.IP) { m.mtx.Lock() node, exists := m.nodes[ip.String()] @@ -254,6 +261,7 @@ func (m *Manager) Attempt(ip net.IP) { 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) { m.mtx.Lock() node, exists := m.nodes[ip.String()] diff --git a/docker/Dockerfile b/docker/Dockerfile index b2b430065..a6a470c5a 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -23,9 +23,9 @@ RUN go mod download 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 TEST_DIRS=`go list -f {{.Dir}} ./... | grep -v /vendor/` golint -set_exit_status $TEST_DIRS +RUN golint -set_exit_status ./... # RUN aligncheck ./... # RUN structcheck -e ./... # RUN varcheck -e ./... diff --git a/logs/doc.go b/logs/doc.go index 4266b366f..3c590740a 100644 --- a/logs/doc.go +++ b/logs/doc.go @@ -3,7 +3,7 @@ // 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. Log level verbosity may be modified at runtime for each individual subsystem diff --git a/logs/logs.go b/logs/logs.go index c81ee0fe2..670c69c6b 100644 --- a/logs/logs.go +++ b/logs/logs.go @@ -35,7 +35,6 @@ package logs import ( "bytes" "fmt" - "github.com/jrick/logrotate/rotator" "os" "path/filepath" "runtime" @@ -43,6 +42,8 @@ import ( "sync" "sync/atomic" "time" + + "github.com/jrick/logrotate/rotator" ) // 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) err := os.MkdirAll(logDir, 0700) 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) 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{ Rotator: r, @@ -342,6 +343,7 @@ func (b *Backend) write(lvl Level, bytesToWrite []byte) { b.mu.Unlock() } +// Close finalizes all log rotators for this backend func (b *Backend) Close() { for _, r := range b.rotators { r.Close() diff --git a/mining/test_utils.go b/mining/test_utils.go index a40037674..118105bd4 100644 --- a/mining/test_utils.go +++ b/mining/test_utils.go @@ -122,6 +122,7 @@ func GenerateDeterministicExtraNonceForTest() uint64 { return extraNonceForTest } +// OpTrueAddress returns an address pointing to a P2SH anyone-can-spend script func OpTrueAddress(prefix util.Bech32Prefix) (util.Address, error) { return util.NewAddressScriptHash(blockdag.OpTrueScript, prefix) } diff --git a/netsync/manager.go b/netsync/manager.go index 8749201d3..fd6a3ad36 100644 --- a/netsync/manager.go +++ b/netsync/manager.go @@ -177,6 +177,10 @@ type SyncManager struct { 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 { // When the current height is less than a known checkpoint we // can use block headers to learn about which blocks comprise diff --git a/peer/peer.go b/peer/peer.go index b58c329f2..f1af514a9 100644 --- a/peer/peer.go +++ b/peer/peer.go @@ -860,6 +860,10 @@ func (p *Peer) PushAddrMsg(addresses []*wire.NetAddress, subnetworkID *subnetwor 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) { msg := wire.NewMsgGetBlockLocator(startHash, stopHash) p.QueueMessage(msg, nil) diff --git a/rpcclient/dag.go b/rpcclient/dag.go index dbb5e2606..fb36cb0b1 100644 --- a/rpcclient/dag.go +++ b/rpcclient/dag.go @@ -561,6 +561,8 @@ func (c *Client) GetRawMempoolVerbose() (map[string]btcjson.GetRawMempoolVerbose // GetSubnetworkAsync RPC invocation (or an applicable error). 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) { res, err := receiveFuture(r) if err != nil { diff --git a/rpcclient/rawrequest.go b/rpcclient/rawrequest.go index 89fbe8a33..a88214900 100644 --- a/rpcclient/rawrequest.go +++ b/rpcclient/rawrequest.go @@ -44,7 +44,7 @@ func (c *Client) RawRequestAsync(method string, params []json.RawMessage) Future // than custom commands. id := c.NextID() rawRequest := &btcjson.Request{ - JsonRPC: "1.0", + JSONRPC: "1.0", ID: id, Method: method, Params: params, diff --git a/server/rpc/rpcserver.go b/server/rpc/rpcserver.go index 7560e5ca1..58d03a8b5 100644 --- a/server/rpc/rpcserver.go +++ b/server/rpc/rpcserver.go @@ -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 // 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 } diff --git a/server/rpc/rpcwebsocket.go b/server/rpc/rpcwebsocket.go index 522ef5a52..58c470853 100644 --- a/server/rpc/rpcwebsocket.go +++ b/server/rpc/rpcwebsocket.go @@ -997,7 +997,7 @@ out: // // RPC quirks can be enabled by the user to avoid compatibility issues // 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 { break out } diff --git a/util/address.go b/util/address.go index d7e69186e..1e7a4df12 100644 --- a/util/address.go +++ b/util/address.go @@ -164,6 +164,7 @@ type AddressPubKeyHash struct { hash [ripemd160.Size]byte } +// NewAddressPubKeyHashFromPublicKey returns a new AddressPubKeyHash from given public key func NewAddressPubKeyHashFromPublicKey(publicKey []byte, prefix Bech32Prefix) (*AddressPubKeyHash, error) { pkHash := Hash160(publicKey) return newAddressPubKeyHash(prefix, pkHash) diff --git a/util/locks/prioritymutex.go b/util/locks/prioritymutex.go index b9ae7a015..574b5b773 100644 --- a/util/locks/prioritymutex.go +++ b/util/locks/prioritymutex.go @@ -31,6 +31,7 @@ type PriorityMutex struct { lowPriorityMutex sync.Mutex } +// NewPriorityMutex returns a new priority mutex func NewPriorityMutex() *PriorityMutex { lock := PriorityMutex{ highPriorityWaiting: newWaitGroup(), @@ -70,7 +71,7 @@ func (mtx *PriorityMutex) HighPriorityReadLock() { mtx.dataMutex.RLock() } -// HighPriorityWriteUnlock unlocks the high-priority read +// HighPriorityReadUnlock unlocks the high-priority read // lock func (mtx *PriorityMutex) HighPriorityReadUnlock() { mtx.highPriorityWaiting.done() diff --git a/wire/msgblock.go b/wire/msgblock.go index 74dee560d..79ef8aef6 100644 --- a/wire/msgblock.go +++ b/wire/msgblock.go @@ -21,7 +21,7 @@ import ( // backing array multiple times. 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 // maxTxPerBlock is the maximum number of transactions that could diff --git a/wire/msggetblocklocator.go b/wire/msggetblocklocator.go index f4b3fb8b5..b14333feb 100644 --- a/wire/msggetblocklocator.go +++ b/wire/msggetblocklocator.go @@ -1,10 +1,16 @@ package wire import ( - "github.com/daglabs/btcd/util/daghash" "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 { StartHash *daghash.Hash StopHash *daghash.Hash