btcd

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2024 License: MIT Imports: 64 Imported by: 0

Documentation

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 = &btcjson.RPCError{
		Code:    btcjson.ErrRPCUnimplemented,
		Message: "Command unimplemented",
	}

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

Errors

View Source
var Cmd = &cobra.Command{
	Use:   "btcd",
	Short: "start btcd endpoint",
	Run: func(cmd *cobra.Command, args []string) {
		if err := Btcd(nil); err != nil {
			btcdLog.Error(err)
			os.Exit(1)
		}
		<-signal.InterruptHandlersDone
	},
}
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.

View Source
var ErrRescanReorg = btcjson.RPCError{
	Code:    btcjson.ErrRPCDatabase,
	Message: "Reorganize",
}

ErrRescanReorg defines the error that is returned when an unrecoverable reorganize is detected during a rescan.

Functions

func Btcd

func Btcd(serverChan chan<- *Server, opts ...Option) error

Btcd is the real main function for btcd. It is necessary to work around the fact that deferred functions do not run when os.Exit() is called. The optional serverChan parameter is mainly used by the service code to be notified with the server once it is setup so it can gracefully stop it when requested from the service control manager.

Types

type Config

type Config struct {
	AddCheckpoints       []string      `long:"addcheckpoint" description:"Add a custom checkpoint.  Format: '<height>:<hash>'"`
	AddPeers             []string      `short:"a" long:"addpeer" description:"Add a peer to connect with at startup"`
	AddrIndex            bool          `` /* 130-byte string literal not displayed */
	AgentBlacklist       []string      `` /* 186-byte string literal not displayed */
	AgentWhitelist       []string      `` /* 309-byte string literal not displayed */
	BanDuration          time.Duration `long:"banduration" description:"How long to ban misbehaving peers.  Valid time units are {s, m, h}.  Minimum 1 second"`
	BanThreshold         uint32        `long:"banthreshold" description:"Maximum allowed ban score before disconnecting and banning misbehaving peers."`
	BlockMaxSize         uint32        `long:"blockmaxsize" description:"Maximum block size in bytes to be used when creating a block"`
	BlockMinSize         uint32        `long:"blockminsize" description:"Minimum block size in bytes to be used when creating a block"`
	BlockMaxWeight       uint32        `long:"blockmaxweight" description:"Maximum block weight to be used when creating a block"`
	BlockMinWeight       uint32        `long:"blockminweight" description:"Minimum block weight to be used when creating a block"`
	BlockPrioritySize    uint32        `long:"blockprioritysize" description:"Size in bytes for high-priority/low-fee transactions when creating a block"`
	BlocksOnly           bool          `long:"blocksonly" description:"Do not accept transactions from remote peers."`
	ConfigFile           string        `short:"C" long:"configfile" description:"Path to configuration file"`
	ConnectPeers         []string      `long:"connect" description:"Connect only to the specified peers at startup"`
	CPUProfile           string        `long:"cpuprofile" description:"Write CPU profile to the specified file"`
	MemoryProfile        string        `long:"memprofile" description:"Write memory profile to the specified file"`
	DataDir              string        `short:"b" long:"datadir" description:"Directory to store data"`
	DbType               string        `long:"dbtype" description:"Database backend to use for the Block Chain"`
	DebugLevel           string        `` /* 275-byte string literal not displayed */
	DropAddrIndex        bool          `long:"dropaddrindex" description:"Deletes the address-based transaction index from the database on start up and then exits."`
	DropCfIndex          bool          `` /* 138-byte string literal not displayed */
	DropTxIndex          bool          `long:"droptxindex" description:"Deletes the hash-based transaction index from the database on start up and then exits."`
	ExternalIPs          []string      `long:"externalip" description:"Add an ip to the list of local addresses we claim to listen on to peers"`
	Generate             bool          `long:"generate" description:"Generate (mine) bitcoins using the CPU"`
	FreeTxRelayLimit     float64       `` /* 140-byte string literal not displayed */
	Listeners            []string      `` /* 127-byte string literal not displayed */
	LogDir               string        `long:"logdir" description:"Directory to log output."`
	MaxOrphanTxs         int           `long:"maxorphantx" description:"Max number of orphan transactions to keep in memory"`
	MaxPeers             int           `long:"maxpeers" description:"Max number of inbound and outbound peers"`
	MiningAddrs          []string      `` /* 184-byte string literal not displayed */
	MinRelayTxFee        float64       `long:"minrelaytxfee" description:"The minimum transaction fee in BTC/kB to be considered a non-zero fee."`
	DisableBanning       bool          `long:"nobanning" description:"Disable banning of misbehaving peers"`
	NoCFilters           bool          `long:"nocfilters" description:"Disable committed filtering (CF) support"`
	DisableCheckpoints   bool          `long:"nocheckpoints" description:"Disable built-in checkpoints.  Don't do this unless you know what you're doing."`
	DisableDNSSeed       bool          `long:"nodnsseed" description:"Disable DNS seeding for peers"`
	DisableListen        bool          `` /* 217-byte string literal not displayed */
	NoOnion              bool          `long:"noonion" description:"Disable connecting to tor hidden services"`
	NoPeerBloomFilters   bool          `long:"nopeerbloomfilters" description:"Disable bloom filtering support"`
	NoRelayPriority      bool          `long:"norelaypriority" description:"Do not require free or low-fee transactions to have high priority for relaying"`
	NoWinService         bool          `` /* 155-byte string literal not displayed */
	DisableRPC           bool          `` /* 165-byte string literal not displayed */
	DisableStallHandler  bool          `` /* 137-byte string literal not displayed */
	DisableTLS           bool          `` /* 127-byte string literal not displayed */
	OnionProxy           string        `long:"onion" description:"Connect to tor hidden services via SOCKS5 proxy (eg. 127.0.0.1:9050)"`
	OnionProxyPass       string        `long:"onionpass" default-mask:"-" description:"Password for onion proxy server"`
	OnionProxyUser       string        `long:"onionuser" description:"Username for onion proxy server"`
	Profile              string        `long:"profile" description:"Enable HTTP profiling on given port -- NOTE port must be between 1024 and 65536"`
	Proxy                string        `long:"proxy" description:"Connect via SOCKS5 proxy (eg. 127.0.0.1:9050)"`
	ProxyPass            string        `long:"proxypass" default-mask:"-" description:"Password for proxy server"`
	ProxyUser            string        `long:"proxyuser" description:"Username for proxy server"`
	Prune                uint64        `` /* 175-byte string literal not displayed */
	RegressionTest       bool          `long:"regtest" description:"Use the regression test network"`
	RejectNonStd         bool          `long:"rejectnonstd" description:"Reject non-standard transactions regardless of the default settings for the active network."`
	RejectReplacement    bool          `` /* 174-byte string literal not displayed */
	RelayNonStd          bool          `long:"relaynonstd" description:"Relay non-standard transactions regardless of the default settings for the active network."`
	RPCCert              string        `long:"rpccert" description:"File containing the certificate file"`
	RPCKey               string        `long:"rpckey" description:"File containing the certificate key"`
	RPCLimitPass         string        `long:"rpclimitpass" default-mask:"-" description:"Password for limited RPC connections"`
	RPCLimitUser         string        `long:"rpclimituser" description:"Username for limited RPC connections"`
	RPCListeners         []string      `long:"rpclisten" description:"Add an interface/port to listen for RPC connections (default port: 8334, testnet: 18334)"`
	RPCMaxClients        int           `long:"rpcmaxclients" description:"Max number of RPC clients for standard connections"`
	RPCMaxConcurrentReqs int           `long:"rpcmaxconcurrentreqs" description:"Max number of concurrent RPC requests that may be processed concurrently"`
	RPCMaxWebsockets     int           `long:"rpcmaxwebsockets" description:"Max number of RPC websocket connections"`
	RPCQuirks            bool          `` /* 151-byte string literal not displayed */
	RPCPass              string        `short:"P" long:"rpcpass" default-mask:"-" description:"Password for RPC connections"`
	RPCUser              string        `short:"u" long:"rpcuser" description:"Username for RPC connections"`
	SigCacheMaxSize      uint          `long:"sigcachemaxsize" description:"The maximum number of entries in the signature verification cache"`
	SimNet               bool          `long:"simnet" description:"Use the simulation test network"`
	SigNet               bool          `long:"signet" description:"Use the signet test network"`
	SigNetChallenge      string        `` /* 188-byte string literal not displayed */
	SigNetSeedNode       []string      `` /* 140-byte string literal not displayed */
	TestNet3             bool          `long:"testnet" description:"Use the test network"`
	TorIsolation         bool          `long:"torisolation" description:"Enable Tor stream isolation by randomizing user credentials for each connection."`
	TrickleInterval      time.Duration `long:"trickleinterval" description:"Minimum time between attempts to send new inventory to a connected peer"`
	UtxoCacheMaxSizeMiB  uint          `long:"utxocachemaxsize" description:"The maximum size in MiB of the UTXO cache"`
	TxIndex              bool          `` /* 142-byte string literal not displayed */
	UserAgentComments    []string      `long:"uacomment" description:"Comment to add to the user agent -- See BIP 14 for more information."`
	Upnp                 bool          `long:"upnp" description:"Use UPnP to map our listening port outside of NAT"`
	ShowVersion          bool          `short:"V" long:"version" description:"Display version information and exit"`
	Whitelists           []string      `long:"whitelist" description:"Add an IP network or IP that will not be banned. (eg. 192.168.1.0/24 or ::1)"`
	// contains filtered or unexported fields
}

config defines the configuration options for btcd.

See loadConfig for details on the configuration load process.

type NAT

type NAT interface {
	// GetExternalAddress Get the external address from outside the NAT.
	GetExternalAddress() (addr net.IP, err error)
	// AddPortMapping Add a port mapping for protocol ("udp" or "tcp") from external port to
	// internal port with description lasting for timeout.
	AddPortMapping(protocol string, externalPort, internalPort int, description string, timeout int) (mappedExternalPort int, err error)
	// DeletePortMapping Remove a previously added port mapping from external port to
	// internal port.
	DeletePortMapping(protocol string, externalPort, internalPort int) (err error)
}

NAT is an interface representing a NAT traversal options for example UPNP or NAT-PMP. It provides methods to query and manipulate this traversal to allow access to services.

func Discover

func Discover() (nat NAT, err error)

Discover searches the local network for a UPnP router returning a NAT for the network if so, nil if not.

type Option

type Option func(*Options)

func WithPassword

func WithPassword(password string) Option

func WithRpcListen

func WithRpcListen(rpcListen string) Option

func WithTestnet

func WithTestnet(testnet bool) Option

func WithUser

func WithUser(user string) Option

type Options

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

type Server

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

Server provides a bitcoin server for handling communications to and from bitcoin peers.

func (*Server) AddBytesReceived

func (s *Server) AddBytesReceived(bytesReceived uint64)

AddBytesReceived adds the passed number of bytes to the total bytes received counter for the server. It is safe for concurrent access.

func (*Server) AddBytesSent

func (s *Server) AddBytesSent(bytesSent uint64)

AddBytesSent adds the passed number of bytes to the total bytes sent counter for the server. It is safe for concurrent access.

func (*Server) AddPeer

func (s *Server) AddPeer(sp *serverPeer)

AddPeer adds a new peer that has already been connected to the server.

func (*Server) AddRebroadcastInventory

func (s *Server) AddRebroadcastInventory(iv *wire.InvVect, data interface{})

AddRebroadcastInventory adds 'iv' to the list of inventories to be rebroadcasted at random intervals until they show up in a block.

func (*Server) AnnounceNewTransactions

func (s *Server) AnnounceNewTransactions(txns []*mempool.TxDesc)

AnnounceNewTransactions generates and relays inventory vectors and 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) BanPeer

func (s *Server) BanPeer(sp *serverPeer)

BanPeer bans a peer that has already been connected to the server by ip.

func (*Server) BroadcastMessage

func (s *Server) BroadcastMessage(msg wire.Message, exclPeers ...*serverPeer)

BroadcastMessage sends msg to all peers currently connected to the server except those in the passed peers to exclude.

func (*Server) ConnectedCount

func (s *Server) ConnectedCount() int32

ConnectedCount returns the number of currently connected peers.

func (*Server) NetTotals

func (s *Server) NetTotals() (uint64, uint64)

NetTotals returns the sum of all bytes received and sent across the network for all peers. It is safe for concurrent access.

func (*Server) OutboundGroupCount

func (s *Server) OutboundGroupCount(key string) int

OutboundGroupCount returns the number of peers connected to the given outbound group key.

func (*Server) RelayInventory

func (s *Server) RelayInventory(invVect *wire.InvVect, data interface{})

RelayInventory relays the passed inventory vector to all connected peers that are not already known to have it.

func (*Server) RemoveRebroadcastInventory

func (s *Server) RemoveRebroadcastInventory(iv *wire.InvVect)

RemoveRebroadcastInventory removes 'iv' from the list of items to be rebroadcasted if present.

func (*Server) ScheduleShutdown

func (s *Server) ScheduleShutdown(duration time.Duration)

ScheduleShutdown schedules a server shutdown after the specified duration. It also dynamically adjusts how often to warn the server is going down based on remaining duration.

func (*Server) Start

func (s *Server) Start()

Start begins accepting connections from peers.

func (*Server) Stop

func (s *Server) Stop() error

Stop gracefully shuts down the server by stopping and disconnecting all peers and the main listener.

func (*Server) TransactionConfirmed

func (s *Server) TransactionConfirmed(tx *btcutil.Tx)

Transaction has one confirmation on the main chain. Now we can mark it as no longer needing rebroadcasting.

func (*Server) UpdatePeerHeights

func (s *Server) UpdatePeerHeights(latestBlkHash *chainhash.Hash, latestHeight int32, updateSource *peer.Peer)

UpdatePeerHeights updates the heights of all peers who have have announced the latest connected main chain block, or a recognized orphan. These height updates allow us to dynamically refresh peer heights, ensuring sync peer selection has access to the latest block heights for each peer.

func (*Server) WaitForShutdown

func (s *Server) WaitForShutdown()

WaitForShutdown blocks until the main listener and peer handlers are stopped.

Directories

Path Synopsis
Package rpcclient implements a websocket-enabled Bitcoin JSON-RPC client.
Package rpcclient implements a websocket-enabled Bitcoin JSON-RPC client.

Jump to

Keyboard shortcuts

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