This is based on https://proposals.decred.org/proposals/c96290a but was modified in order to deal with realities that were unknown at the time of the specification draft. It is large and could not really be broken apart due to the pervasive use of the isTreasuryEnabled flag. It was primarily authored by * Marco Peereboom <marco@peereboom.us> * Dave Collins <davec@conformal.com> * Matheus Degiovani <opensource@matheusd.com> With additional contributions from * Donald Adu-Poku <donald.adu@gmail.com> * Jamie Holdstock <jholdstock@decred.org> Major changes: * Add decentralized treasury agenda, as specified in DCP0006, to all supported nets. * Add functions to determine if the decentralized treasury agenda is active at given block. * Add new opcode OP_TADD that is a nop in txscript but is used to tag scripts that credit the treasury account. This opcode is overloaded for treasurybase and for normal transactions. * Add new opcode OP_TSPEND that is a nop in txscript but is used to tag scripts that debit the treasury account. * Add new opcode OP_TGEN that is a nop in txscript but is used to tag P2PKH and P2SH outputs in a TSpend transaction. * Add functions that detect if a transaction is a valid TAdd, TSpend or treasurybase transaction. * Add error codes that return specific treasurybase/TAdd/TSpend consensus violations. * Modify countSpentOutputs to deal with treasury opcodes accordingly. * Modify indexBlock to skip treasury transactions that do not have inputs. * Add IsTreasuryEnabled call to ChainQueryer interface. * Add treasury logger for debugging and logging the decentralized treasury subsystem. * Add IsTreasuryActive flag to BlockConnectedNtfnsData and BlockDisconnectedNtfnsData. * Modify OP_SSGEN to allow an optional output that contains votes for a TSpend transaction hash. * Add function that returns TSpend votes from an SSGen transaction. * Modify CalcStakeVoteSubsidy so that treasurybase, unlike coinbase, is always awarded the full percentage of the assigned block reward. * Add helper functions to do all TSpend math so that callers don't roll their own. * Modify IsCoinBaseTx to not mistake a TSpend transaction as a coinbase. * Add checkTreasuryBase function that verifies that a treasurybase is properly constructed and pays the right amount to the treasury account. * Add functions to calculate treasury balance for the provided block hash/node. * Add function that verifies if a TSpend has a valid signature. * Add functions to determine if a TSpend is not overspending. * Add function to determine if a TSpend has been mined on the provided chain. * Add functions that count and verifies treasury spend votes. * Modify connectTransaction and disconnectTransactions to deal with the various treasury transactions. * Split CheckTransactionSanity in two functions checkTransactionSanityContextFree and checkTransactionSanityContextual. This is done in order to keep the decentralized treasury, which is always contextual, from infecting the context free checks. * Modify checkTransactionSanityContextual to recognize and verify treasury transactions. * Modify CheckTransactionSanity to deal with treasury transactions. * Split checkBlockSanity in two functions checkBlockSanityContextFree and checkBlockSanityContextual. This is done in order to keep the decentralized treasury, which is always contextual, from infecting the context free checks. * Modify checkBlockSanityContextual to enforce treasurybase and TAdd consensus checks. * Modify checkBlockPositional by unindenting it and adding TSpend consensus enforcement. * Modify checkCoinbaseUniqueHeightWithAddress to deal with the removal of the project subsidy from output 0. * Add checkCoinbaseUniqueHeightWithTreasuryBase that verifies coinbase and treasurybase in the provided block. * Unindent checkBlockContext. * Modify checkTicketRedeemerCommitments and checkVoteInputs to deal with potential tspend votes. * Modify CheckTransactionInputs to skip treasurybase transactions. * Modify CheckTransactionInputs to deal with TSpend transactions. Ensure the provided Pi key is valid and that the signature is valid for the transaction. Ensure that treasury TAdd and TSpend transaction utxo can only be spent after coinbase maturity. * Modify CountSigOps to deal with treasury transactions. * Modify CountP2SHSigOps to deal with treasury transactions. * Modify getStakeTreeFees to skip treasury transactions. Modify totalOutputs to subtract ValueIn 0 for TSpend and treasurybase transactions. * Modify checkTransactionsAndConnect to deal with modified amounts. * Add tspendChecks function that verifies an entire TSpend transaction validity at the point of the provided block. It ensures a TSpend is on a TVI. It ensures the TSpend is in the valid window. It verifies that a TSpend In and Out amounts match. It ensures a TSpend has the ValueIn amount encoded in the OP_RETURN in Out 0. It ensures a TSpend has not been mined before on this chain. It ensures a TSpend has the requisite votes. It ensures a TSpend is not overspending. * Modify checkConnectBlock to call checkTreasuryBase and tspendChecks when treasury agenda is active. * Add two tables to the database. Table "treasury" records the balance as of this block and balance changes that occurred in this block which will become active in CoinbaseMaturity blocks. Table "tspend" records all block hashes where a TSpend has been mined this is to detect forks and prevent a Tspend from being mined more than once. * Modify handleBlockchainNotification to communicate if the treasury agenda is active and skip treasurybase transaction when needed. * Add various Treasury parameters to chaincfg params. * Add hardcoded Tspend signatures in dcr_tmux_simnet_setup.sh. * Add notifytspend and stoptspend calls to the RPC server. notifytspend notifies the mempool when a TSpend transaction arrives. * Modify commit filters V2 to recognize TAdd and TSpend transactions. It was possible to modify V2 instead of introducing V3 because nothing changes from the viewpoint of the wallet and treasury opcodes are disallowed prior to agenda activation. * Modify AddMemPoolTransaction to skip TSpend transactions that would throw the fee estimator off. * Add IsTreasuryAgendaActive, OnTSpendReceived and TSpendMinedOnAncestor to mempool.Config in order to reject/accept TSpends in the mempool. * Modify checkPoolDoubleSpend to ignore treasurybase. * Modify mempool.maybeAcceptTransaction to enforce treasury standardness rules. Don't allow TSpend transactions prior to stake validation height. Skip treasurybase and tspend transactions in the orphan test. Ensure a tspend is in a valid window. Ensure not more than 7 TSpends are active in the mempool. Ensure TSpend has a well-known Pi key. Ensure The provided Pi key was used to sign the transaction. Ensure TSpend was not mined in an ancestor block. Notify subscribers that a valid TSpend was received. * Add standardCoinbaseOpReturn and standardTreasurybaseOpReturn to create an OP_RETURN followed by a data push that little endian encodes the height of the block. Then there are a number of random bytes to ensure that the transaction hash is always random. * Modify createCoinbaseTx to create a coinbase that is valid when treasury is enabled or not. Additionally, alter the transaction version if treasury is enabled. * Add createTreasuryBaseTx that creates a standard treasurybase. * Modify maybeInsertStakeTx to recognize treasurybase and TSpend transactions. * Modify handleTooFewVoters to call createTreasuryBaseTx when the treasury agenda is active. Skip copying treasurybase. * Modify NewBlockTemplate to recognize and deal with treasury transactions. Skip TSpend transaction if block is not a TVI. Skip TSpend transaction if it is not in the proper window. Skip TSpend transaction if a TSpend does not have enough yes votes. Skip TSpend transaction if it overspends the treasury account. Skip TAdd if there are more than 20 TAdds in the block. Create treasurybase if required. Insert valid TAdd/TSpend transactions into stake tree. * Add TreasuryBalance and IsTreasuryAgendaActive to rpcserver Chain interface. * Add gettreasurybalance, sendfromtreasury and sendtotreasury calls to RPC server. * Add notifytspend and stopnotifytspend to RPC websocket commands. * Add simnet miner to generate large number of blocks during rpctests without triggering PoW difficulty increases. This is used to verify various treasury and tspend conditions during CI/CT. * Modify RPC voting wallet to also vote on TSpends. * Add json tests to verify all new opcodes and corner cases in the script engine. * Modify isStakeOpcode to recognize treasury opcodes. * Modify countSigOpsV0 to count TSpends. * Modify handleStakeOutSign to deal with TSpends. * Modify SignTxOutput to recognize TSpends. * Add TSpendSignatureScript that signs a TSpend transaction. * Add TreasuryAddTy and TreasurySpendTy types to the standard scripts. * Add isTreasuryAddScript and isTreasurySpendScript functions that recognize a form of TAdd and TSpend transactions. * Modify ExtractPkScriptAddrs to deal with TAdd and TSpend outputs. * Add TxVersionSeqLock = 2 and TxVersionTreasury = 3 to wire. This is used to discriminate between treasury and non-treasury scripts. * Rig up all functions that need the isTreasuryEnabledflag directly or indirectly. * Shuffle various functions around and export them when they were needed to be called from other packages. * Added and modified numerous tests to verify (hopefully) all corner cases that the decentralized treasury agenda has added.
565 lines
19 KiB
Go
565 lines
19 KiB
Go
// Copyright (c) 2017 The btcsuite developers
|
|
// Copyright (c) 2015-2020 The Decred developers
|
|
// Use of this source code is governed by an ISC
|
|
// license that can be found in the LICENSE file.
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net"
|
|
"time"
|
|
|
|
"github.com/decred/dcrd/blockchain/stake/v3"
|
|
"github.com/decred/dcrd/blockchain/v3"
|
|
"github.com/decred/dcrd/chaincfg/chainhash"
|
|
"github.com/decred/dcrd/chaincfg/v3"
|
|
"github.com/decred/dcrd/dcrutil/v3"
|
|
"github.com/decred/dcrd/internal/mempool"
|
|
"github.com/decred/dcrd/internal/mining"
|
|
"github.com/decred/dcrd/internal/mining/cpuminer"
|
|
"github.com/decred/dcrd/internal/rpcserver"
|
|
"github.com/decred/dcrd/peer/v2"
|
|
"github.com/decred/dcrd/wire"
|
|
)
|
|
|
|
// rpcPeer provides a peer for use with the RPC server and implements the
|
|
// rpcserver.Peer interface.
|
|
type rpcPeer serverPeer
|
|
|
|
// Ensure rpcPeer implements the rpcserver.Peer interface.
|
|
var _ rpcserver.Peer = (*rpcPeer)(nil)
|
|
|
|
// Addr returns the peer address.
|
|
//
|
|
// This function is safe for concurrent access and is part of the rpcserver.Peer
|
|
// interface implementation.
|
|
func (p *rpcPeer) Addr() string {
|
|
return (*serverPeer)(p).Peer.Addr()
|
|
}
|
|
|
|
// Connected returns whether or not the peer is currently connected.
|
|
//
|
|
// This function is safe for concurrent access and is part of the rpcserver.Peer
|
|
// interface implementation.
|
|
func (p *rpcPeer) Connected() bool {
|
|
return (*serverPeer)(p).Peer.Connected()
|
|
}
|
|
|
|
// ID returns the peer id.
|
|
//
|
|
// This function is safe for concurrent access and is part of the rpcserver.Peer
|
|
// interface implementation.
|
|
func (p *rpcPeer) ID() int32 {
|
|
return (*serverPeer)(p).Peer.ID()
|
|
}
|
|
|
|
// Inbound returns whether the peer is inbound.
|
|
//
|
|
// This function is safe for concurrent access and is part of the rpcserver.Peer
|
|
// interface implementation.
|
|
func (p *rpcPeer) Inbound() bool {
|
|
return (*serverPeer)(p).Peer.Inbound()
|
|
}
|
|
|
|
// StatsSnapshot returns a snapshot of the current peer flags and statistics.
|
|
//
|
|
// This function is safe for concurrent access and is part of the rpcserver.Peer
|
|
// interface implementation.
|
|
func (p *rpcPeer) StatsSnapshot() *peer.StatsSnap {
|
|
return (*serverPeer)(p).Peer.StatsSnapshot()
|
|
}
|
|
|
|
// LocalAddr returns the local address of the connection.
|
|
//
|
|
// This function is safe for concurrent access and is part of the rpcserver.Peer
|
|
// interface implementation.
|
|
func (p *rpcPeer) LocalAddr() net.Addr {
|
|
return (*serverPeer)(p).Peer.LocalAddr()
|
|
}
|
|
|
|
// LastPingNonce returns the last ping nonce of the remote peer.
|
|
//
|
|
// This function is safe for concurrent access and is part of the rpcserver.Peer
|
|
// interface implementation.
|
|
func (p *rpcPeer) LastPingNonce() uint64 {
|
|
return (*serverPeer)(p).Peer.LastPingNonce()
|
|
}
|
|
|
|
// IsTxRelayDisabled returns whether or not the peer has disabled transaction
|
|
// relay.
|
|
//
|
|
// This function is safe for concurrent access and is part of the rpcserver.Peer
|
|
// interface implementation.
|
|
func (p *rpcPeer) IsTxRelayDisabled() bool {
|
|
return (*serverPeer)(p).relayTxDisabled()
|
|
}
|
|
|
|
// BanScore returns the current integer value that represents how close the peer
|
|
// is to being banned.
|
|
//
|
|
// This function is safe for concurrent access and is part of the rpcserver.Peer
|
|
// interface implementation.
|
|
func (p *rpcPeer) BanScore() uint32 {
|
|
return (*serverPeer)(p).banScore.Int()
|
|
}
|
|
|
|
// rpcConnManager provides a connection manager for use with the RPC server and
|
|
// implements the rpcserver.ConnManager interface.
|
|
type rpcConnManager struct {
|
|
server *server
|
|
}
|
|
|
|
// Ensure rpcConnManager implements the rpcserver.ConnManager interface.
|
|
var _ rpcserver.ConnManager = (*rpcConnManager)(nil)
|
|
|
|
// Connect adds the provided address as a new outbound peer. The permanent flag
|
|
// indicates whether or not to make the peer persistent and reconnect if the
|
|
// connection is lost. Attempting to connect to an already existing peer will
|
|
// return an error.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) Connect(addr string, permanent bool) error {
|
|
replyChan := make(chan error)
|
|
cm.server.query <- connectNodeMsg{
|
|
addr: addr,
|
|
permanent: permanent,
|
|
reply: replyChan,
|
|
}
|
|
return <-replyChan
|
|
}
|
|
|
|
// RemoveByID removes the peer associated with the provided id from the list of
|
|
// persistent peers. Attempting to remove an id that does not exist will return
|
|
// an error.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) RemoveByID(id int32) error {
|
|
replyChan := make(chan error)
|
|
cm.server.query <- removeNodeMsg{
|
|
cmp: func(sp *serverPeer) bool { return sp.ID() == id },
|
|
reply: replyChan,
|
|
}
|
|
return <-replyChan
|
|
}
|
|
|
|
// RemoveByAddr removes the peer associated with the provided address from the
|
|
// list of persistent peers. Attempting to remove an address that does not
|
|
// exist will return an error.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) RemoveByAddr(addr string) error {
|
|
replyChan := make(chan error)
|
|
cm.server.query <- removeNodeMsg{
|
|
cmp: func(sp *serverPeer) bool { return sp.Addr() == addr },
|
|
reply: replyChan,
|
|
}
|
|
|
|
// Cancel the connection if it could still be pending.
|
|
err := <-replyChan
|
|
if err != nil {
|
|
cm.server.query <- cancelPendingMsg{
|
|
addr: addr,
|
|
reply: replyChan,
|
|
}
|
|
|
|
return <-replyChan
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DisconnectByID disconnects the peer associated with the provided id. This
|
|
// applies to both inbound and outbound peers. Attempting to remove an id that
|
|
// does not exist will return an error.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) DisconnectByID(id int32) error {
|
|
replyChan := make(chan error)
|
|
cm.server.query <- disconnectNodeMsg{
|
|
cmp: func(sp *serverPeer) bool { return sp.ID() == id },
|
|
reply: replyChan,
|
|
}
|
|
return <-replyChan
|
|
}
|
|
|
|
// DisconnectByAddr disconnects the peer associated with the provided address.
|
|
// This applies to both inbound and outbound peers. Attempting to remove an
|
|
// address that does not exist will return an error.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) DisconnectByAddr(addr string) error {
|
|
replyChan := make(chan error)
|
|
cm.server.query <- disconnectNodeMsg{
|
|
cmp: func(sp *serverPeer) bool { return sp.Addr() == addr },
|
|
reply: replyChan,
|
|
}
|
|
return <-replyChan
|
|
}
|
|
|
|
// ConnectedCount returns the number of currently connected peers.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) ConnectedCount() int32 {
|
|
return cm.server.ConnectedCount()
|
|
}
|
|
|
|
// NetTotals returns the sum of all bytes received and sent across the network
|
|
// for all peers.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) NetTotals() (uint64, uint64) {
|
|
return cm.server.NetTotals()
|
|
}
|
|
|
|
// ConnectedPeers returns an array consisting of all connected peers.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) ConnectedPeers() []rpcserver.Peer {
|
|
replyChan := make(chan []*serverPeer)
|
|
cm.server.query <- getPeersMsg{reply: replyChan}
|
|
serverPeers := <-replyChan
|
|
|
|
// Convert to RPC server peers.
|
|
peers := make([]rpcserver.Peer, 0, len(serverPeers))
|
|
for _, sp := range serverPeers {
|
|
peers = append(peers, (*rpcPeer)(sp))
|
|
}
|
|
return peers
|
|
}
|
|
|
|
// PersistentPeers returns an array consisting of all the added persistent
|
|
// peers.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) PersistentPeers() []rpcserver.Peer {
|
|
replyChan := make(chan []*serverPeer)
|
|
cm.server.query <- getAddedNodesMsg{reply: replyChan}
|
|
serverPeers := <-replyChan
|
|
|
|
// Convert to generic peers.
|
|
peers := make([]rpcserver.Peer, 0, len(serverPeers))
|
|
for _, sp := range serverPeers {
|
|
peers = append(peers, (*rpcPeer)(sp))
|
|
}
|
|
return peers
|
|
}
|
|
|
|
// BroadcastMessage sends the provided message to all currently connected peers.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) BroadcastMessage(msg wire.Message) {
|
|
cm.server.BroadcastMessage(msg)
|
|
}
|
|
|
|
// AddRebroadcastInventory adds the provided inventory to the list of
|
|
// inventories to be rebroadcast at random intervals until they show up in a
|
|
// block.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) AddRebroadcastInventory(iv *wire.InvVect, data interface{}) {
|
|
cm.server.AddRebroadcastInventory(iv, data)
|
|
}
|
|
|
|
// RelayTransactions generates and relays inventory vectors for all of the
|
|
// passed transactions to all connected peers.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) RelayTransactions(txns []*dcrutil.Tx) {
|
|
cm.server.relayTransactions(txns)
|
|
}
|
|
|
|
// AddedNodeInfo returns information describing persistent (added) nodes.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (cm *rpcConnManager) AddedNodeInfo() []rpcserver.Peer {
|
|
serverPeers := cm.server.AddedNodeInfo()
|
|
|
|
// Convert to RPC server peers.
|
|
peers := make([]rpcserver.Peer, 0, len(serverPeers))
|
|
for _, sp := range serverPeers {
|
|
peers = append(peers, (*rpcPeer)(sp))
|
|
}
|
|
|
|
return peers
|
|
}
|
|
|
|
// Lookup defines the DNS lookup function to be used.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.ConnManager interface implementation.
|
|
func (*rpcConnManager) Lookup(host string) ([]net.IP, error) {
|
|
return dcrdLookup(host)
|
|
}
|
|
|
|
// rpcSyncMgr provides a block manager for use with the RPC server and
|
|
// implements the rpcserver.SyncManager interface.
|
|
type rpcSyncMgr struct {
|
|
server *server
|
|
blockMgr *blockManager
|
|
}
|
|
|
|
// Ensure rpcSyncMgr implements the rpcserver.SyncManager interface.
|
|
var _ rpcserver.SyncManager = (*rpcSyncMgr)(nil)
|
|
|
|
// IsCurrent returns whether or not the sync manager believes the chain is
|
|
// current as compared to the rest of the network.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.SyncManager interface implementation.
|
|
func (b *rpcSyncMgr) IsCurrent() bool {
|
|
return b.blockMgr.IsCurrent()
|
|
}
|
|
|
|
// SubmitBlock submits the provided block to the network after processing it
|
|
// locally.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.SyncManager interface implementation.
|
|
func (b *rpcSyncMgr) SubmitBlock(block *dcrutil.Block, flags blockchain.BehaviorFlags) (bool, error) {
|
|
return b.blockMgr.ProcessBlock(block, flags)
|
|
}
|
|
|
|
// SyncPeer returns the id of the current peer being synced with.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.SyncManager interface implementation.
|
|
func (b *rpcSyncMgr) SyncPeerID() int32 {
|
|
return b.blockMgr.SyncPeerID()
|
|
}
|
|
|
|
// LocateBlocks returns the hashes of the blocks after the first known block in
|
|
// the locator until the provided stop hash is reached, or up to the provided
|
|
// max number of block hashes.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.SyncManager interface implementation.
|
|
func (b *rpcSyncMgr) LocateBlocks(locator blockchain.BlockLocator, hashStop *chainhash.Hash, maxHashes uint32) []chainhash.Hash {
|
|
return b.server.chain.LocateBlocks(locator, hashStop, maxHashes)
|
|
}
|
|
|
|
// TipGeneration returns the entire generation of blocks stemming from the
|
|
// parent of the current tip.
|
|
func (b *rpcSyncMgr) TipGeneration() ([]chainhash.Hash, error) {
|
|
return b.blockMgr.TipGeneration()
|
|
}
|
|
|
|
// SyncHeight returns latest known block being synced to.
|
|
func (b *rpcSyncMgr) SyncHeight() int64 {
|
|
return b.blockMgr.SyncHeight()
|
|
}
|
|
|
|
// ProcessTransaction relays the provided transaction validation and insertion
|
|
// into the memory pool.
|
|
func (b *rpcSyncMgr) ProcessTransaction(tx *dcrutil.Tx, allowOrphans bool,
|
|
rateLimit bool, allowHighFees bool, tag mempool.Tag) ([]*dcrutil.Tx, error) {
|
|
return b.blockMgr.ProcessTransaction(tx, allowOrphans,
|
|
rateLimit, allowHighFees, tag)
|
|
}
|
|
|
|
// rpcUtxoEntry represents a utxo entry for use with the RPC server and
|
|
// implements the rpcserver.UtxoEntry interface.
|
|
type rpcUtxoEntry struct {
|
|
*blockchain.UtxoEntry
|
|
}
|
|
|
|
// Ensure rpcUtxoEntry implements the rpcserver.UtxoEntry interface.
|
|
var _ rpcserver.UtxoEntry = (*rpcUtxoEntry)(nil)
|
|
|
|
// ToUtxoEntry returns the underlying UtxoEntry instance.
|
|
func (u *rpcUtxoEntry) ToUtxoEntry() *blockchain.UtxoEntry {
|
|
return u.UtxoEntry
|
|
}
|
|
|
|
// rpcChain provides a chain for use with the RPC server and
|
|
// implements the rpcserver.Chain interface.
|
|
type rpcChain struct {
|
|
*blockchain.BlockChain
|
|
}
|
|
|
|
// Ensure rpcChain implements the rpcserver.Chain interface.
|
|
var _ rpcserver.Chain = (*rpcChain)(nil)
|
|
|
|
// ConvertUtxosToMinimalOutputs converts the contents of a UTX to a series of
|
|
// minimal outputs. It does this so that these can be passed to stake subpackage
|
|
// functions, where they will be evaluated for correctness.
|
|
func (c *rpcChain) ConvertUtxosToMinimalOutputs(entry rpcserver.UtxoEntry) []*stake.MinimalOutput {
|
|
return blockchain.ConvertUtxosToMinimalOutputs(entry.ToUtxoEntry())
|
|
}
|
|
|
|
// FetchUtxoEntry loads and returns the unspent transaction output entry for the
|
|
// passed hash from the point of view of the end of the main chain.
|
|
//
|
|
// NOTE: Requesting a hash for which there is no data will NOT return an error.
|
|
// Instead both the entry and the error will be nil. This is done to allow
|
|
// pruning of fully spent transactions. In practice this means the caller must
|
|
// check if the returned entry is nil before invoking methods on it.
|
|
//
|
|
// This function is safe for concurrent access however the returned entry (if
|
|
// any) is NOT.
|
|
func (c *rpcChain) FetchUtxoEntry(txHash *chainhash.Hash) (rpcserver.UtxoEntry, error) {
|
|
utxo, err := c.BlockChain.FetchUtxoEntry(txHash)
|
|
if utxo == nil || err != nil {
|
|
return nil, err
|
|
}
|
|
return &rpcUtxoEntry{UtxoEntry: utxo}, nil
|
|
}
|
|
|
|
// rpcClock provides a clock for use with the RPC server and
|
|
// implements the rpcserver.Clock interface.
|
|
type rpcClock struct{}
|
|
|
|
// Ensure rpcClock implements the rpcserver.Clock interface.
|
|
var _ rpcserver.Clock = (*rpcClock)(nil)
|
|
|
|
// Now returns the current local time.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.Clock interface implementation.
|
|
func (*rpcClock) Now() time.Time {
|
|
return time.Now()
|
|
}
|
|
|
|
// Since returns the time elapsed since t.
|
|
//
|
|
// This function is safe for concurrent access and is part of the
|
|
// rpcserver.Clock interface implementation.
|
|
func (*rpcClock) Since(t time.Time) time.Duration {
|
|
return time.Since(t)
|
|
}
|
|
|
|
// rpcLogManager provides a log manager for use with the RPC server and
|
|
// implements the rpcserver.LogManager interface.
|
|
type rpcLogManager struct{}
|
|
|
|
// Ensure rpcLogManager implements the rpcserver.LogManager interface.
|
|
var _ rpcserver.LogManager = (*rpcLogManager)(nil)
|
|
|
|
// SupportedSubsystems returns a sorted slice of the supported subsystems for
|
|
// logging purposes.
|
|
//
|
|
// This function is part of the rpcserver.LogManager interface implementation.
|
|
func (*rpcLogManager) SupportedSubsystems() []string {
|
|
return supportedSubsystems()
|
|
}
|
|
|
|
// ParseAndSetDebugLevels attempts to parse the specified debug level and set
|
|
// the levels accordingly. An appropriate error is returned if anything is
|
|
// invalid.
|
|
//
|
|
// This function is part of the rpcserver.LogManager interface implementation.
|
|
func (*rpcLogManager) ParseAndSetDebugLevels(debugLevel string) error {
|
|
return parseAndSetDebugLevels(debugLevel)
|
|
}
|
|
|
|
// rpcSanityChecker provides a block sanity checker for use with the RPC and
|
|
// implements the rpcserver.SanityChecker interface.
|
|
type rpcSanityChecker struct {
|
|
chain *blockchain.BlockChain
|
|
timeSource blockchain.MedianTimeSource
|
|
chainParams *chaincfg.Params
|
|
}
|
|
|
|
// Ensure rpcSanityChecker implements the rpcserver.SanityChecker interface.
|
|
var _ rpcserver.SanityChecker = (*rpcSanityChecker)(nil)
|
|
|
|
// CheckBlockSanity checks the correctness of the provided block
|
|
// per consensus. An appropriate error is returned if anything is
|
|
// invalid.
|
|
//
|
|
// This function is part of the rpcserver.SanityChecker interface implementation.
|
|
func (s *rpcSanityChecker) CheckBlockSanity(block *dcrutil.Block) error {
|
|
pHash := &block.MsgBlock().Header.PrevBlock
|
|
isTreasuryEnabled, err := s.chain.IsTreasuryAgendaActive(pHash)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return blockchain.CheckBlockSanity(block, s.timeSource, s.chainParams,
|
|
isTreasuryEnabled)
|
|
}
|
|
|
|
// rpcBlockTemplater provides a block template generator for use with the
|
|
// RPC server and implements the rpcserver.BlockTemplater interface.
|
|
type rpcBlockTemplater struct {
|
|
*mining.BgBlkTmplGenerator
|
|
}
|
|
|
|
// Ensure rpcBlockTemplater implements the rpcserver.BlockTemplater interface.
|
|
var _ rpcserver.BlockTemplater = (*rpcBlockTemplater)(nil)
|
|
|
|
// Subscribe returns a TemplateSubber which has functions to retrieve
|
|
// a channel that produces the stream of block templates and to stop
|
|
// the stream when the caller no longer wishes to receive new templates.
|
|
func (t *rpcBlockTemplater) Subscribe() rpcserver.TemplateSubber {
|
|
return t.BgBlkTmplGenerator.Subscribe()
|
|
}
|
|
|
|
// rpcCPUMiner provides a CPU miner for use with the RPC and implements the
|
|
// rpcserver.CPUMiner interface.
|
|
type rpcCPUMiner struct {
|
|
miner *cpuminer.CPUMiner
|
|
}
|
|
|
|
// Ensure rpcCPUMiner implements the rpcserver.CPUMiner interface.
|
|
var _ rpcserver.CPUMiner = (*rpcCPUMiner)(nil)
|
|
|
|
// GenerateNBlocks generates the requested number of blocks.
|
|
func (c *rpcCPUMiner) GenerateNBlocks(ctx context.Context, n uint32) ([]*chainhash.Hash, error) {
|
|
if c.miner == nil {
|
|
return nil, errors.New("Block generation is disallowed without a " +
|
|
"CPU miner.")
|
|
}
|
|
|
|
return c.miner.GenerateNBlocks(ctx, n)
|
|
}
|
|
|
|
// IsMining returns whether or not the CPU miner has been started and is
|
|
// therefore currently mining.
|
|
func (c *rpcCPUMiner) IsMining() bool {
|
|
if c.miner == nil {
|
|
return false
|
|
}
|
|
|
|
return c.miner.IsMining()
|
|
}
|
|
|
|
// HashesPerSecond returns the number of hashes per second the mining process
|
|
// is performing.
|
|
func (c *rpcCPUMiner) HashesPerSecond() float64 {
|
|
if c.miner == nil {
|
|
return 0
|
|
}
|
|
|
|
return c.miner.HashesPerSecond()
|
|
}
|
|
|
|
// NumWorkers returns the number of workers which are running to solve blocks.
|
|
func (c *rpcCPUMiner) NumWorkers() int32 {
|
|
if c.miner == nil {
|
|
return 0
|
|
}
|
|
|
|
return c.miner.NumWorkers()
|
|
}
|
|
|
|
// SetNumWorkers sets the number of workers to create which solve blocks.
|
|
func (c *rpcCPUMiner) SetNumWorkers(numWorkers int32) {
|
|
if c.miner != nil {
|
|
c.miner.SetNumWorkers(numWorkers)
|
|
}
|
|
}
|