rpcserver

package
v1.6.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 23, 2021 License: ISC Imports: 47 Imported by: 0

README

rpcserver

Build Status ISC License Doc

Overview

Package rpcserver includes all RPC server interfaces, types, and pieces of code pertaining to implementing the RPC server.

License

Package rpcserver is licensed under the copyfree ISC License.

Documentation

Overview

Package rpcserver includes all RPC server interfaces, types, and pieces of code pertaining to implementing the RPC server.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrRPCUnimplemented is an error returned to RPC clients when the
	// provided command is recognized, but not implemented.
	ErrRPCUnimplemented = &vcljson.RPCError{
		Code:    vcljson.ErrRPCUnimplemented,
		Message: "Command unimplemented",
	}

	// ErrRPCNoWallet is an error returned to RPC clients when the provided
	// command is recognized as a wallet command.
	ErrRPCNoWallet = &vcljson.RPCError{
		Code:    vcljson.ErrRPCNoWallet,
		Message: "This implementation does not implement wallet commands",
	}
)

Errors

View Source
var ErrClientQuit = errors.New("client quit")

ErrClientQuit describes the error where a client send is not processed due to the client having already been disconnected or dropped.

Functions

func UseLogger

func UseLogger(logger slog.Logger)

UseLogger uses a specified Logger to output package logging info. This should be used in preference to SetLogWriter if the caller is also using slog.

Types

type AddrIndexer

type AddrIndexer interface {
	// EntriesForAddress returns a slice of details which identify each transaction,
	// including a block region, that involves the passed address according to the
	// specified number to skip, number requested, and whether or not the results
	// should be reversed.  It also returns the number actually skipped since it
	// could be less in the case where there are not enough entries.
	//
	// NOTE: These results only include transactions confirmed in blocks.  See the
	// UnconfirmedTxnsForAddress method for obtaining unconfirmed transactions
	// that involve a given address.
	EntriesForAddress(dbTx database.Tx, addr vclutil.Address, numToSkip,
		numRequested uint32, reverse bool) ([]indexers.TxIndexEntry, uint32, error)

	// UnconfirmedTxnsForAddress returns all transactions currently in the
	// unconfirmed (memory-only) address index that involve the passed address.
	// Unsupported address types are ignored and will result in no results.
	UnconfirmedTxnsForAddress(addr vclutil.Address) []*vclutil.Tx
}

AddrIndexer provides an interface for retrieving transactions for a given address.

The interface contract requires that all of these methods are safe for concurrent access.

type AddrManager

type AddrManager interface {
	// LocalAddresses returns a summary of local addresses information for
	// the getnetworkinfo rpc.
	LocalAddresses() []addrmgr.LocalAddr
}

AddrManager represents an address manager for use with the RPC server.

The interface contract requires that all of these methods are safe for concurrent access.

type BlockTemplater

type BlockTemplater interface {
	// ForceRegen asks the block templater to generate a new template immediately.
	ForceRegen()

	// Subscribe subscribes a client for block template updates.  The returned
	// template subscription contains 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.
	Subscribe() TemplateSubber

	// CurrentTemplate returns the current template associated with the block
	// templater along with any associated error.
	CurrentTemplate() (*mining.BlockTemplate, error)

	// UpdateBlockTime updates the timestamp in the passed header to the current
	// time while taking into account the consensus rules.
	UpdateBlockTime(header *wire.BlockHeader) error
}

BlockTemplater represents a source of block templates for use with the RPC server.

The interface contract requires that all of these methods are safe for concurrent access.

type CPUMiner

type CPUMiner interface {
	// GenerateNBlocks generates the requested number of blocks.
	GenerateNBlocks(ctx context.Context, n uint32) ([]*chainhash.Hash, error)

	// IsMining returns whether or not the CPU miner has been started and is
	// therefore currently mining.
	IsMining() bool

	// HashesPerSecond returns the number of hashes per second the mining process
	// is performing.
	HashesPerSecond() float64

	// NumWorkers returns the number of workers which are running to solve blocks.
	NumWorkers() int32

	// SetNumWorkers sets the number of workers to create which solve blocks.
	SetNumWorkers(numWorkers int32)
}

CPUMiner represents a CPU miner for use with the RPC server. The purpose of this interface is to allow an alternative implementation to be used for testing.

The interface contract requires that all of these methods are safe for concurrent access.

type Chain

type Chain interface {
	// BestSnapshot returns information about the current best chain block and
	// related state as of the current point in time.  The returned instance must be
	// treated as immutable since it is shared by all callers.
	BestSnapshot() *blockchain.BestState

	// BlockByHash returns the block for the given hash, regardless of whether the
	// block is part of the main chain or not.
	BlockByHash(hash *chainhash.Hash) (*vclutil.Block, error)

	// BlockByHeight returns the block at the given height in the main chain.
	BlockByHeight(height int64) (*vclutil.Block, error)

	// BlockHashByHeight returns the hash of the block at the given height in the
	// main chain.
	BlockHashByHeight(height int64) (*chainhash.Hash, error)

	// BlockHeightByHash returns the height of the block with the given hash in the
	// main chain.
	BlockHeightByHash(hash *chainhash.Hash) (int64, error)

	// CalcNextRequiredStakeDifficulty calculates the required stake difficulty for
	// the block after the end of the current best chain based on the active stake
	// difficulty retarget rules.
	CalcNextRequiredStakeDifficulty() (int64, error)

	// CalcWantHeight calculates the height of the final block of the previous
	// interval given a block height.
	CalcWantHeight(interval, height int64) int64

	// ChainTips returns information, in JSON-RPC format, about all of the currently
	// known chain tips in the block index.
	ChainTips() []blockchain.ChainTipInfo

	// ChainWork returns the total work up to and including the block of the
	// provided block hash.
	ChainWork(hash *chainhash.Hash) (*big.Int, error)

	// CheckExpiredTicket returns whether or not a ticket was ever expired.
	CheckExpiredTickets(hashes []chainhash.Hash) []bool

	// CheckLiveTicket returns whether or not a ticket exists in the live ticket
	// treap of the best node.
	CheckLiveTicket(hash chainhash.Hash) bool

	// CheckLiveTickets returns a slice of bools representing whether each ticket
	// exists in the live ticket treap of the best node.
	CheckLiveTickets(hashes []chainhash.Hash) []bool

	// CheckMissedTickets returns a slice of bools representing whether each ticket
	// hash has been missed in the live ticket treap of the best node.
	CheckMissedTickets(hashes []chainhash.Hash) []bool

	// 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.
	ConvertUtxosToMinimalOutputs(entry UtxoEntry) []*stake.MinimalOutput

	// CountVoteVersion returns the total number of version votes for the current
	// rule change activation interval.
	CountVoteVersion(version uint32) (uint32, error)

	// EstimateNextStakeDifficulty estimates the next stake difficulty by pretending
	// the provided number of tickets will be purchased in the remainder of the
	// interval unless the flag to use max tickets is set in which case it will use
	// the max possible number of tickets that can be purchased in the remainder of
	// the interval.
	EstimateNextStakeDifficulty(newTickets int64, useMaxTickets bool) (int64, error)

	// 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 must NOT return an error.
	// Instead both the entry and the error must 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.
	FetchUtxoEntry(txHash *chainhash.Hash) (UtxoEntry, error)

	// FetchUtxoStats returns statistics on the current utxo set.
	FetchUtxoStats() (*blockchain.UtxoStats, error)

	// GetStakeVersions returns a cooked array of StakeVersions.  We do this in
	// order to not bloat memory by returning raw blocks.
	GetStakeVersions(hash *chainhash.Hash, count int32) ([]blockchain.StakeVersions, error)

	// GetVoteCounts returns the vote counts for the specified version and
	// deployment identifier for the current rule change activation interval.
	GetVoteCounts(version uint32, deploymentID string) (blockchain.VoteCounts, error)

	// GetVoteInfo returns information on consensus deployment agendas
	// and their respective states at the provided hash, for the provided
	// deployment version.
	GetVoteInfo(hash *chainhash.Hash, version uint32) (*blockchain.VoteInfo, error)

	// HeaderByHash returns the block header identified by the given hash or an
	// error if it doesn't exist.  Note that this will return headers from both the
	// main chain and any side chains.
	HeaderByHash(hash *chainhash.Hash) (wire.BlockHeader, error)

	// HeaderByHeight returns the block header at the given height in the main
	// chain.
	HeaderByHeight(height int64) (wire.BlockHeader, error)

	// HeightRange returns a range of block hashes for the given start and end
	// heights.  It is inclusive of the start height and exclusive of the end
	// height.  In other words, it is the half open range [startHeight, endHeight).
	//
	// The end height will be limited to the current main chain height.
	HeightRange(startHeight, endHeight int64) ([]chainhash.Hash, error)

	// IsCurrent returns whether or not the chain believes it is current.  Several
	// factors are used to guess, but the key factors that allow the chain to
	// believe it is current are:
	//  - Total amount of cumulative work is more than the minimum known work
	//    specified by the parameters for the network
	//  - Latest block has a timestamp newer than 24 hours ago
	IsCurrent() bool

	// LiveTickets returns all currently live tickets.
	LiveTickets() ([]chainhash.Hash, error)

	// LocateHeaders returns the headers of the blocks after the first known block
	// in the locator until the provided stop hash is reached, or up to a max of
	// wire.MaxBlockHeadersPerMsg headers.
	//
	// In addition, there are two special cases:
	//
	// - When no locators are provided, the stop hash is treated as a request for
	//   that header, so it will either return the header for the stop hash itself
	//   if it is known, or nil if it is unknown
	// - When locators are provided, but none of them are known, headers starting
	//   after the genesis block will be returned
	LocateHeaders(locator blockchain.BlockLocator, hashStop *chainhash.Hash) []wire.BlockHeader

	// LotteryDataForBlock returns lottery data for a given block in the block
	// chain, including side chain blocks.
	LotteryDataForBlock(hash *chainhash.Hash) ([]chainhash.Hash, int, [6]byte, error)

	// MainChainHasBlock returns whether or not the block with the given hash is in
	// the main chain.
	MainChainHasBlock(hash *chainhash.Hash) bool

	// MaxBlockSize returns the maximum permitted block size for the block AFTER
	// the end of the current best chain.
	MaxBlockSize() (int64, error)

	// MissedTickets returns all currently missed tickets.
	MissedTickets() ([]chainhash.Hash, error)

	// NextThresholdState returns the current rule change threshold state of the
	// given deployment ID for the block AFTER the provided block hash.
	NextThresholdState(hash *chainhash.Hash, version uint32, deploymentID string) (blockchain.ThresholdStateTuple, error)

	// StateLastChangedHeight returns the height at which the provided consensus
	// deployment agenda last changed state.  Note that, unlike the
	// NextThresholdState function, this function returns the information as of the
	// passed block hash.
	StateLastChangedHeight(hash *chainhash.Hash, version uint32, deploymentID string) (int64, error)

	// TicketPoolValue returns the current value of all the locked funds in the
	// ticket pool.
	TicketPoolValue() (vclutil.Amount, error)

	// TicketsWithAddress returns a slice of ticket hashes that are currently
	// live corresponding to the given address.
	TicketsWithAddress(address vclutil.Address, isTreasuryEnabled bool) ([]chainhash.Hash, error)

	// TipGeneration returns the entire generation of blocks stemming from the
	// parent of the current tip.
	TipGeneration() ([]chainhash.Hash, error)

	// TreasuryBalance returns the treasury balance at the provided block.
	TreasuryBalance(*chainhash.Hash) (*blockchain.TreasuryBalanceInfo, error)

	// IsTreasuryAgendaActive returns whether or not the treasury agenda vote, as
	// defined in DCP0006, has passed and is now active for the block AFTER the
	// given block.
	IsTreasuryAgendaActive(*chainhash.Hash) (bool, error)

	// FetchTSpend returns all blocks where the treasury spend tx
	// identified by the specified hash can be found.
	FetchTSpend(chainhash.Hash) ([]chainhash.Hash, error)

	// TSpendCountVotes returns the votes for the specified tspend up to
	// the specified block.
	TSpendCountVotes(*chainhash.Hash, *vclutil.Tx) (int64, int64, error)
}

Chain represents a chain for use with the RPC server.

The interface contract requires that all of these methods are safe for concurrent access.

type Clock

type Clock interface {
	// Now returns the current local time.
	Now() time.Time

	// Since returns the time elapsed since t.
	Since(t time.Time) time.Duration
}

Clock represents a clock for use with the RPC server. The purpose of this interface is to allow an alternative implementation to be used for testing.

The interface contract requires that all of these methods are safe for concurrent access.

type Config

type Config struct {
	// Listeners defines a slice of listeners for which the RPC server will
	// take ownership of and accept connections.  Since the RPC server takes
	// ownership of these listeners, they will be closed when the RPC server
	// is stopped.
	Listeners []net.Listener

	// StartupTime is the unix timestamp for when the server that is hosting
	// the RPC server started.
	StartupTime int64

	// ConnMgr defines the connection manager for the RPC server to use.  It
	// provides the RPC server with a means to do things such as add,
	// remove, connect, disconnect, and query peers as well as other
	// connection-related data and tasks.
	ConnMgr ConnManager

	// SyncMgr defines the sync manager for the RPC server to use.
	SyncMgr SyncManager

	// ExistsAddresser defines the exist addresser for the RPC server to
	// use.
	ExistsAddresser ExistsAddresser

	// These fields allow the RPC server to interface with the local block
	// chain data and state.
	TimeSource    blockchain.MedianTimeSource
	Chain         Chain
	SanityChecker SanityChecker
	ChainParams   *chaincfg.Params
	DB            database.DB
	FeeEstimator  FeeEstimator
	Services      wire.ServiceFlag

	// SubsidyCache defines a cache for efficient access to consensus-critical
	// subsidy calculations.
	SubsidyCache *standalone.SubsidyCache

	// AddrManager defines a concurrency safe address manager for caching
	// potential peers on the network.
	AddrManager AddrManager

	// Clock defines the clock for the RPC server to use.
	Clock Clock

	// TxMempooler defines the transaction memory pool to interact with.
	TxMempooler TxMempooler

	// These fields allow the RPC server to interface with mining.
	//
	// BlockTemplater generates block templates, CPUMiner solves
	// templates using the CPU.  CPU mining is typically only useful
	// for test purposes when doing regression or simulation testing.
	BlockTemplater BlockTemplater
	CPUMiner       CPUMiner

	// TxIndexer defines the optional transaction indexer for the RPC server to
	// use.
	TxIndexer TxIndexer

	// AddrIndexer defines the optional address indexer for the RPC server to use.
	AddrIndexer AddrIndexer

	// NetInfo defines a slice of the available networks.
	NetInfo []types.NetworksResult

	// MinRelayTxFee defines the minimum transaction fee in Atoms/1000 bytes to be
	// considered a non-zero fee.
	MinRelayTxFee vclutil.Amount

	// Proxy defines the proxy that is being used for connections.
	Proxy string

	// These fields define the username and password for RPC connections and
	// limited RPC connections.
	RPCUser      string
	RPCPass      string
	RPCLimitUser string
	RPCLimitPass string

	// RPCMaxClients defines the max number of RPC clients for standard
	// connections.
	RPCMaxClients int

	// RPCMaxConcurrentReqs defines the max number of RPC requests that may be
	// processed concurrently.
	RPCMaxConcurrentReqs int

	// RPCMaxWebsockets defines the max number of RPC websocket connections.
	RPCMaxWebsockets int

	// TestNet represents whether or not the server is using testnet.
	TestNet bool

	// MiningAddrs is a list of payment addresses to use for the generated blocks.
	MiningAddrs []vclutil.Address

	// AllowUnsyncedMining indicates whether block templates should be created even
	// when the chain is not fully synced.
	AllowUnsyncedMining bool

	// MaxProtocolVersion is the max protocol version that the server supports.
	MaxProtocolVersion uint32

	// UserAgentVersion is the user agent version and is used to help identify
	// ourselves to other peers.
	UserAgentVersion string

	// LogManager defines the log manager for the RPC server to use.
	LogManager LogManager

	// Filterer defines the filterer for the RPC server to use.
	Filterer Filterer

	// FiltererV2 defines the V2 filterer for the RPC server to use.
	FiltererV2 FiltererV2
}

Config is a descriptor containing the RPC server configuration.

type ConnManager

type ConnManager interface {
	// 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.
	Connect(addr string, permanent bool) error

	// 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.
	RemoveByID(id int32) error

	// 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.
	RemoveByAddr(addr string) error

	// 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.
	DisconnectByID(id int32) error

	// 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.
	DisconnectByAddr(addr string) error

	// ConnectedCount returns the number of currently connected peers.
	ConnectedCount() int32

	// NetTotals returns the sum of all bytes received and sent across the
	// network for all peers.
	NetTotals() (uint64, uint64)

	// ConnectedPeers returns an array consisting of all connected peers.
	ConnectedPeers() []Peer

	// PersistentPeers returns an array consisting of all the persistent
	// peers.
	PersistentPeers() []Peer

	// BroadcastMessage sends the provided message to all currently
	// connected peers.
	BroadcastMessage(msg wire.Message)

	// AddRebroadcastInventory adds the provided inventory to the list of
	// inventories to be rebroadcast at random intervals until they show up
	// in a block.
	AddRebroadcastInventory(iv *wire.InvVect, data interface{})

	// RelayTransactions generates and relays inventory vectors for all of
	// the passed transactions to all connected peers.
	RelayTransactions(txns []*vclutil.Tx)

	// AddedNodeInfo returns information describing persistent (added) nodes.
	AddedNodeInfo() []Peer

	// Lookup defines the DNS lookup function to be used.
	Lookup(host string) ([]net.IP, error)
}

ConnManager represents a connection manager for use with the RPC server.

The interface contract requires that all of these methods are safe for concurrent access.

type ExistsAddresser

type ExistsAddresser interface {
	// ExistsAddress returns whether or not an address has been seen before.
	ExistsAddress(addr vclutil.Address) (bool, error)

	// ExistsAddresses returns whether or not each address in a slice of
	// addresses has been seen before.
	ExistsAddresses(addrs []vclutil.Address) ([]bool, error)
}

ExistsAddresser represents a source of exists address methods for the RPC server. These methods return whether or not an address or addresses have been seen on the blockchain.

The interface contract requires that all of these methods are safe for concurrent access.

ExistsAddresser may be nil. The RPC server must check for the presence of an ExistsAddresser before calling methods associated with it.

type FeeEstimator

type FeeEstimator interface {
	// EstimateFee calculates the suggested fee for a transaction to be
	// confirmed in at most `targetConfs` blocks after publishing with a
	// high degree of certainty.
	EstimateFee(targetConfs int32) (vclutil.Amount, error)
}

FeeEstimator provides an interface that tracks historical data for published and mined transactions in order to estimate fees to be used in new transactions for confirmation within a target block window.

The interface contract requires that all of these methods are safe for concurrent access.

type Filterer deprecated

type Filterer interface {
	// FilterByBlockHash returns the serialized contents of a block's regular or
	// extended committed filter.
	FilterByBlockHash(h *chainhash.Hash, filterType wire.FilterType) ([]byte, error)

	// FilterHeaderByBlockHash returns the serialized contents of a block's regular
	// or extended committed filter header.
	FilterHeaderByBlockHash(h *chainhash.Hash, filterType wire.FilterType) ([]byte, error)
}

Filterer provides an interface for retrieving a block's committed filter or committed filter header.

The interface contract requires that all of these methods are safe for concurrent access.

Deprecated: This will be removed in the next major version. Use FiltererV2 instead.

type FiltererV2

type FiltererV2 interface {
	// FilterByBlockHash returns the version 2 GCS filter for the given block hash
	// when it exists.  This function returns the filters regardless of whether or
	// not their associated block is part of the main chain.
	//
	// An error of type blockchain.NoFilterError must be returned when the filter
	// for the given block hash does not exist.
	FilterByBlockHash(hash *chainhash.Hash) (*gcs.FilterV2, error)
}

FiltererV2 provides an interface for retrieving a block's version 2 GCS filter.

The interface contract requires that all of these methods are safe for concurrent access.

type LogManager

type LogManager interface {
	// SupportedSubsystems returns a sorted slice of the supported subsystems for
	// logging purposes.
	SupportedSubsystems() []string

	// ParseAndSetDebugLevels attempts to parse the specified debug level and set
	// the levels accordingly.  An appropriate error must be returned if anything
	// is invalid.
	ParseAndSetDebugLevels(debugLevel string) error
}

LogManager represents a log manager for use with the RPC server.

The interface contract does NOT require that these methods are safe for concurrent access.

type Peer

type Peer interface {
	// Addr returns the peer address.
	Addr() string

	// Connected returns whether or not the peer is currently connected.
	Connected() bool

	// ID returns the peer id.
	ID() int32

	// Inbound returns whether the peer is inbound.
	Inbound() bool

	// StatsSnapshot returns a snapshot of the current peer flags and statistics.
	StatsSnapshot() *peer.StatsSnap

	// LocalAddr returns the local address of the connection or nil if the peer
	// is not currently connected.
	LocalAddr() net.Addr

	// LastPingNonce returns the last ping nonce of the remote peer.
	LastPingNonce() uint64

	// IsTxRelayDisabled returns whether or not the peer has disabled
	// transaction relay.
	IsTxRelayDisabled() bool

	// BanScore returns the current integer value that represents how close
	// the peer is to being banned.
	BanScore() uint32
}

Peer represents a peer for use with the RPC server.

The interface contract requires that all of these methods are safe for concurrent access.

type SanityChecker

type SanityChecker interface {
	// CheckBlockSanity checks the correctness of the provided block
	// per consensus.
	CheckBlockSanity(block *vclutil.Block) error
}

SanityChecker represents a block sanity checker for use with the RPC server.

The interface contract requires that all of these methods are safe for concurrent access.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server provides a concurrent safe RPC server to a chain server.

func New

func New(config *Config) (*Server, error)

New returns a new instance of the Server struct.

func (*Server) NotifyBlockConnected

func (s *Server) NotifyBlockConnected(block *vclutil.Block)

NotifyBlockConnected notifies websocket clients that have registered for block updates when a block is connected to the main chain.

func (*Server) NotifyBlockDisconnected

func (s *Server) NotifyBlockDisconnected(block *vclutil.Block)

NotifyBlockDisconnected notifies websocket clients that have registered for block updates when a block is disconnected from the main chain.

func (*Server) NotifyNewTickets

func (s *Server) NotifyNewTickets(tnd *blockchain.TicketNotificationsData)

NotifyNewTickets notifies websocket clients that have registered for maturing ticket updates.

func (*Server) NotifyNewTransactions

func (s *Server) NotifyNewTransactions(txns []*vclutil.Tx)

NotifyNewTransactions notifies both websocket and getblocktemplate long poll clients of the passed transactions. This function should be called whenever new transactions are added to the mempool.

func (*Server) NotifyReorganization

func (s *Server) NotifyReorganization(rd *blockchain.ReorganizationNtfnsData)

NotifyReorganization notifies websocket clients that have registered for block updates when the blockchain is beginning a reorganization.

func (*Server) NotifySpentAndMissedTickets

func (s *Server) NotifySpentAndMissedTickets(tnd *blockchain.TicketNotificationsData)

NotifySpentAndMissedTickets notifies websocket clients that have registered for spent and missed ticket updates.

func (*Server) NotifyStakeDifficulty

func (s *Server) NotifyStakeDifficulty(stnd *StakeDifficultyNtfnData)

NotifyStakeDifficulty notifies websocket clients that have registered for stake difficulty updates.

func (*Server) NotifyTSpend

func (s *Server) NotifyTSpend(tx *vclutil.Tx)

NotifyTSpend notifies websocket clients that have registered to receive new tspends in the mempool.

func (*Server) NotifyWinningTickets

func (s *Server) NotifyWinningTickets(wtnd *WinningTicketsNtfnData)

NotifyWinningTickets notifies websocket clients that have registered for winning ticket updates.

func (*Server) NotifyWork

func (s *Server) NotifyWork(templateNtfn *mining.TemplateNtfn)

NotifyWork notifies websocket clients that have registered for new mining work.

func (*Server) RequestedProcessShutdown

func (s *Server) RequestedProcessShutdown() <-chan struct{}

RequestedProcessShutdown returns a channel that is sent to when an authorized RPC client requests the process to shutdown. If the request can not be read immediately, it is dropped.

func (*Server) Run

func (s *Server) Run(ctx context.Context)

Run starts the rpc server and its listeners. It blocks until the provided context is cancelled.

func (*Server) WebsocketHandler

func (s *Server) WebsocketHandler(conn *websocket.Conn, remoteAddr string, authenticated bool, isAdmin bool)

WebsocketHandler handles a new websocket client by creating a new wsClient, starting it, and blocking until the connection closes. Since it blocks, it must be run in a separate goroutine. It should be invoked from the websocket server handler which runs each new connection in a new goroutine thereby satisfying the requirement.

type StakeDifficultyNtfnData

type StakeDifficultyNtfnData struct {
	BlockHash       chainhash.Hash
	BlockHeight     int64
	StakeDifficulty int64
}

StakeDifficultyNtfnData is the data that is used to generate stake difficulty notifications.

type SyncManager

type SyncManager interface {
	// IsCurrent returns whether or not the sync manager believes the chain
	// is current as compared to the rest of the network.
	IsCurrent() bool

	// SubmitBlock submits the provided block to the network after
	// processing it locally.
	SubmitBlock(block *vclutil.Block, flags blockchain.BehaviorFlags) (bool, error)

	// SyncPeerID returns the id of the current peer being synced with.
	SyncPeerID() int32

	// 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.
	LocateBlocks(locator blockchain.BlockLocator, hashStop *chainhash.Hash,
		maxHashes uint32) []chainhash.Hash

	// TipGeneration returns the entire generation of blocks stemming from the
	// parent of the current tip.
	TipGeneration() ([]chainhash.Hash, error)

	// SyncHeight returns latest known block being synced to.
	SyncHeight() int64

	// ProcessTransaction relays the provided transaction validation and
	// insertion into the memory pool.
	ProcessTransaction(tx *vclutil.Tx, allowOrphans bool, rateLimit bool,
		allowHighFees bool, tag mempool.Tag) ([]*vclutil.Tx, error)
}

SyncManager represents a sync manager for use with the RPC server.

The interface contract requires that all of these methods are safe for concurrent access.

type TemplateSubber

type TemplateSubber interface {
	// C returns a channel that produces a stream of block templates as
	// each new template is generated.
	C() <-chan *mining.TemplateNtfn

	// Stop prevents any future template updates from being delivered and
	// unsubscribes the associated subscription.
	Stop()
}

TemplaterSubber represents a block template subscription.

The interface contract requires that all these methods are safe for concurrent access.

type TxIndexer

type TxIndexer interface {
	// Entry returns details for the provided transaction hash from the transaction
	// index.  The block region contained in the result can in turn be used to load
	// the raw transaction bytes.  When there is no entry for the provided hash, nil
	// must be returned for the both the entry and the error.
	Entry(hash *chainhash.Hash) (*indexers.TxIndexEntry, error)
}

TxIndexer provides an interface for retrieving details for a given transaction hash.

The interface contract requires that all of these methods are safe for concurrent access.

type TxMempooler

type TxMempooler interface {
	// HaveTransactions returns whether or not the passed transactions
	// already exist in the main pool or in the orphan pool.
	HaveTransactions(hashes []*chainhash.Hash) []bool

	// TxDescs returns a slice of descriptors for all the transactions in
	// the pool. The descriptors must be treated as read only.
	TxDescs() []*mempool.TxDesc

	// VerboseTxDescs returns a slice of verbose descriptors for all the
	// transactions in the pool. The descriptors must be treated as read
	// only.
	VerboseTxDescs() []*mempool.VerboseTxDesc

	// Count returns the number of transactions in the main pool. It does
	// not include the orphan pool.
	Count() int

	// FetchTransaction returns the requested transaction from the
	// transaction pool. This only fetches from the main transaction pool
	// and does not include orphans.
	FetchTransaction(txHash *chainhash.Hash) (*vclutil.Tx, error)

	// TSpendHashes returns the hashes of the treasury spend transactions
	// currently in the mempool.
	TSpendHashes() []chainhash.Hash
}

TxMempooler represents a source of mempool transaction data for the RPC server. Methods assume the existence of a main pool and an orphans pool.

The interface contract requires that all of these methods are safe for concurrent access.

type UtxoEntry

type UtxoEntry interface {
	// ToUtxoEntry returns the underlying UtxoEntry instance.
	ToUtxoEntry() *blockchain.UtxoEntry

	// TransactionType returns the type of the transaction the utxo entry
	// represents.
	TransactionType() stake.TxType

	// IsOutputSpent returns whether or not the provided output index has been
	// spent based upon the current state of the unspent transaction output view
	// the entry was obtained from.
	//
	// Returns true if the output index references an output that does not exist
	// either due to it being invalid or because the output is not part of the view
	// due to previously being spent/pruned.
	IsOutputSpent(outputIndex uint32) bool

	// BlockHeight returns the height of the block containing the transaction the
	// utxo entry represents.
	BlockHeight() int64

	// TxVersion returns the version of the transaction the utxo represents.
	TxVersion() uint16

	// AmountByIndex returns the amount of the provided output index.
	//
	// Returns 0 if the output index references an output that does not exist
	// either due to it being invalid or because the output is not part of the view
	// due to previously being spent/pruned.
	AmountByIndex(outputIndex uint32) int64

	// ScriptVersionByIndex returns the public key script for the provided output
	// index.
	//
	// Returns 0 if the output index references an output that does not exist
	// either due to it being invalid or because the output is not part of the view
	// due to previously being spent/pruned.
	ScriptVersionByIndex(outputIndex uint32) uint16

	// PkScriptByIndex returns the public key script for the provided output index.
	//
	// Returns nil if the output index references an output that does not exist
	// either due to it being invalid or because the output is not part of the view
	// due to previously being spent/pruned.
	PkScriptByIndex(outputIndex uint32) []byte

	// IsCoinBase returns whether or not the transaction the utxo entry represents
	// is a coinbase.
	IsCoinBase() bool
}

UtxoEntry represents a utxo entry for use with the RPC server.

The interface contract does NOT require that these methods are safe for concurrent access.

type WinningTicketsNtfnData

type WinningTicketsNtfnData struct {
	BlockHash   chainhash.Hash
	BlockHeight int64
	Tickets     []chainhash.Hash
}

WinningTicketsNtfnData is the data that is used to generate winning ticket notifications (which indicate a block and the tickets eligible to vote on it).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL