daemon

package
v0.0.0-...-9802667 Latest Latest
Warning

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

Go to latest
Published: May 27, 2018 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrDisconnectReasons invalid version
	ErrDisconnectInvalidVersion gnet.DisconnectReason = errors.New("Invalid version")
	// ErrDisconnectIntroductionTimeout timeout
	ErrDisconnectIntroductionTimeout gnet.DisconnectReason = errors.New("Version timeout")
	// ErrDisconnectVersionSendFailed version send failed
	ErrDisconnectVersionSendFailed gnet.DisconnectReason = errors.New("Version send failed")
	// ErrDisconnectIsBlacklisted is blacklisted
	ErrDisconnectIsBlacklisted gnet.DisconnectReason = errors.New("Blacklisted")
	// ErrDisconnectSelf self connnect
	ErrDisconnectSelf gnet.DisconnectReason = errors.New("Self connect")
	// ErrDisconnectConnectedTwice connect twice
	ErrDisconnectConnectedTwice gnet.DisconnectReason = errors.New("Already connected")
	// ErrDisconnectIdle idle
	ErrDisconnectIdle gnet.DisconnectReason = errors.New("Idle")
	// ErrDisconnectNoIntroduction no introduction
	ErrDisconnectNoIntroduction gnet.DisconnectReason = errors.New("First message was not an Introduction")
	// ErrDisconnectIPLimitReached ip limit reached
	ErrDisconnectIPLimitReached gnet.DisconnectReason = errors.New("Maximum number of connections for this IP was reached")
	// ErrDisconnectOtherError this is returned when a seemingly impossible error is encountered
	// e.g. net.Conn.Addr() returns an invalid ip:port
	ErrDisconnectOtherError gnet.DisconnectReason = errors.New("Incomprehensible error")
)

Todo - verify that minimum/maximum connections are working - keep max connections - maintain minimum number of outgoing connections per server?

Functions

func MakeSearchMap

func MakeSearchMap(addrs []string) map[string]struct{}

MakeSearchMap returns a search indexed map for use in filters

Types

type AnnounceBlocksMessage

type AnnounceBlocksMessage struct {
	MaxBkSeq uint64
	// contains filtered or unexported fields
}

AnnounceBlocksMessage tells a peer our highest known BkSeq. The receiving peer can choose to send GetBlocksMessage in response

func NewAnnounceBlocksMessage

func NewAnnounceBlocksMessage(seq uint64) *AnnounceBlocksMessage

NewAnnounceBlocksMessage creates message

func (*AnnounceBlocksMessage) Handle

func (abm *AnnounceBlocksMessage) Handle(mc *gnet.MessageContext,
	daemon interface{}) error

Handle handles message

func (*AnnounceBlocksMessage) Process

func (abm *AnnounceBlocksMessage) Process(d *Daemon)

Process process message

type AnnounceTxnsMessage

type AnnounceTxnsMessage struct {
	Txns []cipher.SHA256
	// contains filtered or unexported fields
}

AnnounceTxnsMessage tells a peer that we have these transactions

func NewAnnounceTxnsMessage

func NewAnnounceTxnsMessage(txns []cipher.SHA256) *AnnounceTxnsMessage

NewAnnounceTxnsMessage creates announce txns message

func (*AnnounceTxnsMessage) GetTxns

func (atm *AnnounceTxnsMessage) GetTxns() []cipher.SHA256

GetTxns returns txns

func (*AnnounceTxnsMessage) Handle

func (atm *AnnounceTxnsMessage) Handle(mc *gnet.MessageContext,
	daemon interface{}) error

Handle handle message

func (*AnnounceTxnsMessage) Process

func (atm *AnnounceTxnsMessage) Process(d *Daemon)

Process process message

type AsyncMessage

type AsyncMessage interface {
	Process(d *Daemon)
}

AsyncMessage messages that perform an action when received must implement this interface. Process() is called after the message is pulled off of messageEvent channel. Messages should place themselves on the messageEvent channel in their Handle() method required by gnet.

type BlockchainProgress

type BlockchainProgress struct {
	// Our current blockchain length
	Current uint64 `json:"current"`
	// Our best guess at true blockchain length
	Highest uint64 `json:"highest"`
	Peers   []struct {
		Address string `json:"address"`
		Height  uint64 `json:"height"`
	} `json:"peers"`
}

BlockchainProgress current sync blockchain status

type Config

type Config struct {
	Daemon   DaemonConfig
	Messages MessagesConfig
	Pool     PoolConfig
	Pex      pex.Config
	Gateway  GatewayConfig
	Visor    VisorConfig
}

Config subsystem configurations

func NewConfig

func NewConfig() Config

NewConfig returns a Config with defaults set

type ConnectEvent

type ConnectEvent struct {
	Addr      string
	Solicited bool
}

ConnectEvent generated when a client connects

type Connection

type Connection struct {
	ID           int    `json:"id"`
	Addr         string `json:"address"`
	LastSent     int64  `json:"last_sent"`
	LastReceived int64  `json:"last_received"`
	// Whether the connection is from us to them (true, outgoing),
	// or from them to us (false, incoming)
	Outgoing bool `json:"outgoing"`
	// Whether the client has identified their version, mirror etc
	Introduced bool   `json:"introduced"`
	Mirror     uint32 `json:"mirror"`
	ListenPort uint16 `json:"listen_port"`
}

Connection a connection's state within the daemon

type ConnectionError

type ConnectionError struct {
	Addr  string
	Error error
}

ConnectionError represent a failure to connect/dial a connection, with context

type ConnectionMirrors

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

ConnectionMirrors records mirror for connection

func NewConnectionMirrors

func NewConnectionMirrors() *ConnectionMirrors

NewConnectionMirrors create ConnectionMirrors instance.

func (*ConnectionMirrors) Add

func (cm *ConnectionMirrors) Add(addr string, mirror uint32)

Add adds connection mirror

func (*ConnectionMirrors) Get

func (cm *ConnectionMirrors) Get(addr string) (uint32, bool)

Get returns the mirror of connection

func (*ConnectionMirrors) Remove

func (cm *ConnectionMirrors) Remove(addr string)

Remove remove connection mirror

type Connections

type Connections struct {
	Connections []*Connection `json:"connections"`
}

Connections an array of connections Arrays must be wrapped in structs to avoid certain javascript exploits

type CullMatchFunc

type CullMatchFunc func(addr string, t time.Time) (bool, error)

CullMatchFunc function for checking if the connection need to be culled

type Daemon

type Daemon struct {
	// Daemon configuration
	Config DaemonConfig

	// Components
	Messages *Messages
	Pool     *Pool
	Pex      *pex.Pex
	Gateway  *Gateway
	Visor    *Visor

	DefaultConnections []string

	// log buffer
	LogBuff bytes.Buffer
	// contains filtered or unexported fields
}

Daemon stateful properties of the daemon

func NewDaemon

func NewDaemon(config Config, db *bolt.DB, defaultConns []string) (*Daemon, error)

NewDaemon returns a Daemon with primitives allocated

func (*Daemon) GetListenPort

func (dm *Daemon) GetListenPort(addr string) uint16

GetListenPort returns the ListenPort for a given address. If no port is found, 0 is returned.

func (*Daemon) Run

func (dm *Daemon) Run() error

Run main loop for peer/connection management. Send anything to the quit channel to shut it down.

func (*Daemon) Shutdown

func (dm *Daemon) Shutdown()

Shutdown Terminates all subsystems safely. To stop the Daemon run loop, send a value over the quit channel provided to Init. The Daemon run loop must be stopped before calling this function.

type DaemonConfig

type DaemonConfig struct {
	// Application version. TODO -- manage version better
	Version int32
	// IP Address to serve on. Leave empty for automatic assignment
	Address string
	// TCP/UDP port for connections
	Port int
	// Directory where application data is stored
	DataDirectory string
	// How often to check and initiate an outgoing connection if needed
	OutgoingRate time.Duration
	// How often to re-attempt to fill any missing private (aka required)
	// connections
	PrivateRate time.Duration
	// Number of outgoing connections to maintain
	OutgoingMax int
	// Maximum number of connections to try at once
	PendingMax int
	// How long to wait for a version packet
	IntroductionWait time.Duration
	// How often to check for peers that have decided to stop communicating
	CullInvalidRate time.Duration
	// How many connections are allowed from the same base IP
	IPCountsMax int
	// Disable all networking activity
	DisableNetworking bool
	// Don't make outgoing connections
	DisableOutgoingConnections bool
	// Don't allow incoming connections
	DisableIncomingConnections bool
	// Run on localhost and only connect to localhost peers
	LocalhostOnly bool
	// Log ping and pong messages
	LogPings bool
}

DaemonConfig configuration for the Daemon

func NewDaemonConfig

func NewDaemonConfig() DaemonConfig

NewDaemonConfig creates daemon config

type DisconnectEvent

type DisconnectEvent struct {
	Addr   string
	Reason gnet.DisconnectReason
}

DisconnectEvent generated when a connection terminated

type ExpectIntroductions

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

ExpectIntroductions records connections that are expecting introduction msg.

func NewExpectIntroductions

func NewExpectIntroductions() *ExpectIntroductions

NewExpectIntroductions creates a ExpectIntroduction instance

func (*ExpectIntroductions) Add

func (ei *ExpectIntroductions) Add(addr string, tm time.Time)

Add adds expecting introduction connection

func (*ExpectIntroductions) CullInvalidConns

func (ei *ExpectIntroductions) CullInvalidConns(f CullMatchFunc) ([]string, error)

CullInvalidConns cull connections that match the matchFunc

func (*ExpectIntroductions) Get

func (ei *ExpectIntroductions) Get(addr string) (time.Time, bool)

Get returns the time of speicific address

func (*ExpectIntroductions) Remove

func (ei *ExpectIntroductions) Remove(addr string)

Remove removes connection

type Gateway

type Gateway struct {
	Config GatewayConfig
	// contains filtered or unexported fields
}

Gateway RPC interface wrapper for daemon state

func NewGateway

func NewGateway(c GatewayConfig, d *Daemon) *Gateway

NewGateway create and init an Gateway instance.

func (*Gateway) CreateTransaction

func (gw *Gateway) CreateTransaction(params wallet.CreateTransactionParams) (*coin.Transaction, []wallet.UxBalance, error)

CreateTransaction creates a transaction based upon parameters in wallet.CreateTransactionParams

func (*Gateway) CreateWallet

func (gw *Gateway) CreateWallet(wltName string, options wallet.Options) (*wallet.Wallet, error)

CreateWallet creates wallet

func (*Gateway) DecryptWallet

func (gw *Gateway) DecryptWallet(wltID string, password []byte) (*wallet.Wallet, error)

DecryptWallet decrypts wallet

func (*Gateway) EncryptWallet

func (gw *Gateway) EncryptWallet(wltName string, password []byte) (*wallet.Wallet, error)

EncryptWallet encrypts the wallet

func (*Gateway) GetAddrUxOuts

func (gw *Gateway) GetAddrUxOuts(addresses []cipher.Address) ([]*historydb.UxOut, error)

GetAddrUxOuts gets all the address affected UxOuts.

func (*Gateway) GetAddressCount

func (gw *Gateway) GetAddressCount() (uint64, error)

GetAddressCount returns count number of unique address with uxouts > 0.

func (*Gateway) GetAddressTxns

func (gw *Gateway) GetAddressTxns(a cipher.Address) (*visor.TransactionResults, error)

GetAddressTxns returns a *visor.TransactionResults

func (*Gateway) GetAllUnconfirmedTxns

func (gw *Gateway) GetAllUnconfirmedTxns() []visor.UnconfirmedTxn

GetAllUnconfirmedTxns returns all unconfirmed transactions

func (*Gateway) GetBalanceOfAddrs

func (gw *Gateway) GetBalanceOfAddrs(addrs []cipher.Address) ([]wallet.BalancePair, error)

GetBalanceOfAddrs gets balance of given addresses

func (*Gateway) GetBlockByHash

func (gw *Gateway) GetBlockByHash(hash cipher.SHA256) (block coin.SignedBlock, ok bool)

GetBlockByHash returns the block by hash

func (*Gateway) GetBlockBySeq

func (gw *Gateway) GetBlockBySeq(seq uint64) (block coin.SignedBlock, ok bool)

GetBlockBySeq returns blcok by seq

func (*Gateway) GetBlockchainMetadata

func (gw *Gateway) GetBlockchainMetadata() (*visor.BlockchainMetadata, error)

GetBlockchainMetadata returns a *visor.BlockchainMetadata

func (*Gateway) GetBlockchainProgress

func (gw *Gateway) GetBlockchainProgress() *BlockchainProgress

GetBlockchainProgress returns a *BlockchainProgress

func (*Gateway) GetBlocks

func (gw *Gateway) GetBlocks(start, end uint64) (*visor.ReadableBlocks, error)

GetBlocks returns a *visor.ReadableBlocks

func (*Gateway) GetBlocksInDepth

func (gw *Gateway) GetBlocksInDepth(vs []uint64) (*visor.ReadableBlocks, error)

GetBlocksInDepth returns blocks in different depth

func (*Gateway) GetBuildInfo

func (gw *Gateway) GetBuildInfo() visor.BuildInfo

GetBuildInfo returns node build info.

func (*Gateway) GetConnection

func (gw *Gateway) GetConnection(addr string) *Connection

GetConnection returns a *Connection of specific address

func (*Gateway) GetConnections

func (gw *Gateway) GetConnections() *Connections

GetConnections returns a *Connections

func (*Gateway) GetDefaultConnections

func (gw *Gateway) GetDefaultConnections() []string

GetDefaultConnections returns default connections

func (*Gateway) GetExchgConnection

func (gw *Gateway) GetExchgConnection() []string

GetExchgConnection returns all exchangeable connections, including private and public

func (*Gateway) GetHealth

func (gw *Gateway) GetHealth() (*Health, error)

GetHealth returns statistics about the running node

func (*Gateway) GetLastBlocks

func (gw *Gateway) GetLastBlocks(num uint64) (*visor.ReadableBlocks, error)

GetLastBlocks get last N blocks

func (*Gateway) GetRichlist

func (gw *Gateway) GetRichlist(includeDistribution bool) (visor.Richlist, error)

GetRichlist returns rich list as desc order.

func (*Gateway) GetTimeNow

func (gw *Gateway) GetTimeNow() uint64

GetTimeNow returns the current Unix time

func (*Gateway) GetTransaction

func (gw *Gateway) GetTransaction(txid cipher.SHA256) (tx *visor.Transaction, err error)

GetTransaction returns transaction by txid

func (*Gateway) GetTransactionResult

func (gw *Gateway) GetTransactionResult(txid cipher.SHA256) (*visor.TransactionResult, error)

GetTransactionResult gets transaction result by txid.

func (*Gateway) GetTransactions

func (gw *Gateway) GetTransactions(flts ...visor.TxFilter) ([]visor.Transaction, error)

GetTransactions returns transactions filtered by zero or more visor.TxFilter

func (*Gateway) GetTrustConnections

func (gw *Gateway) GetTrustConnections() []string

GetTrustConnections returns all trusted connections, including private and public

func (*Gateway) GetUnconfirmedTxns

func (gw *Gateway) GetUnconfirmedTxns(addrs []cipher.Address) []visor.UnconfirmedTxn

GetUnconfirmedTxns returns addresses related unconfirmed transactions

func (*Gateway) GetUnspent

func (gw *Gateway) GetUnspent() blockdb.UnspentPool

GetUnspent returns the unspent pool

func (*Gateway) GetUnspentOutputs

func (gw *Gateway) GetUnspentOutputs(filters ...OutputsFilter) (*visor.ReadableOutputSet, error)

GetUnspentOutputs gets unspent outputs and returns the filtered results, Note: all filters will be executed as the pending sequence in 'AND' mode.

func (*Gateway) GetUxOutByID

func (gw *Gateway) GetUxOutByID(id cipher.SHA256) (*historydb.UxOut, error)

GetUxOutByID gets UxOut by hash id.

func (*Gateway) GetWallet

func (gw *Gateway) GetWallet(wltID string) (*wallet.Wallet, error)

GetWallet returns wallet by id

func (*Gateway) GetWalletBalance

func (gw *Gateway) GetWalletBalance(wltID string) (wallet.BalancePair, error)

GetWalletBalance returns balance pair of specific wallet

func (*Gateway) GetWalletDir

func (gw *Gateway) GetWalletDir() (string, error)

GetWalletDir returns path for storing wallet files

func (*Gateway) GetWalletSeed

func (gw *Gateway) GetWalletSeed(id string, password []byte) (string, error)

GetWalletSeed returns seed of wallet of given id, returns wallet.ErrWalletNotEncrypted if the wallet is not encrypted.

func (*Gateway) GetWalletUnconfirmedTxns

func (gw *Gateway) GetWalletUnconfirmedTxns(wltID string) ([]visor.UnconfirmedTxn, error)

GetWalletUnconfirmedTxns returns all unconfirmed transactions in given wallet

func (*Gateway) GetWallets

func (gw *Gateway) GetWallets() (wallet.Wallets, error)

GetWallets returns wallets

func (*Gateway) InjectBroadcastTransaction

func (gw *Gateway) InjectBroadcastTransaction(txn coin.Transaction) error

InjectBroadcastTransaction injects and broadcasts a transaction

func (*Gateway) IsWalletAPIEnabled

func (gw *Gateway) IsWalletAPIEnabled() bool

IsWalletAPIEnabled returns if all wallet related apis are disabled

func (*Gateway) NewAddresses

func (gw *Gateway) NewAddresses(wltID string, password []byte, n uint64) ([]cipher.Address, error)

NewAddresses generate addresses in given wallet

func (*Gateway) ReloadWallets

func (gw *Gateway) ReloadWallets() error

ReloadWallets reloads all wallets

func (*Gateway) ResendTransaction

func (gw *Gateway) ResendTransaction(txn cipher.SHA256) *ResendResult

ResendTransaction resent the transaction and return a *ResendResult

func (*Gateway) ResendUnconfirmedTxns

func (gw *Gateway) ResendUnconfirmedTxns() (rlt *ResendResult)

ResendUnconfirmedTxns resents all unconfirmed transactions

func (*Gateway) Shutdown

func (gw *Gateway) Shutdown()

Shutdown closes the Gateway

func (*Gateway) Spend

func (gw *Gateway) Spend(wltID string, password []byte, coins uint64, dest cipher.Address) (*coin.Transaction, error)

Spend spends coins from given wallet and broadcast it, set password as nil if wallet is not encrypted, otherwise the password must be provied. return transaction or error.

func (*Gateway) UnloadWallet

func (gw *Gateway) UnloadWallet(id string) error

UnloadWallet removes wallet of given id from memory.

func (*Gateway) UpdateWalletLabel

func (gw *Gateway) UpdateWalletLabel(wltID, label string) error

UpdateWalletLabel updates the label of wallet

type GatewayConfig

type GatewayConfig struct {
	BufferSize      int
	EnableWalletAPI bool
}

GatewayConfig configuration set of gateway.

func NewGatewayConfig

func NewGatewayConfig() GatewayConfig

NewGatewayConfig create and init an GatewayConfig

type GetBlocksMessage

type GetBlocksMessage struct {
	LastBlock       uint64
	RequestedBlocks uint64
	// contains filtered or unexported fields
}

GetBlocksMessage sent to request blocks since LastBlock

func NewGetBlocksMessage

func NewGetBlocksMessage(lastBlock uint64, requestedBlocks uint64) *GetBlocksMessage

NewGetBlocksMessage creates GetBlocksMessage

func (*GetBlocksMessage) Handle

func (gbm *GetBlocksMessage) Handle(mc *gnet.MessageContext,
	daemon interface{}) error

Handle handles message

func (*GetBlocksMessage) Process

func (gbm *GetBlocksMessage) Process(d *Daemon)

Process should send number to be requested, with request

type GetPeersMessage

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

GetPeersMessage sent to request peers

func NewGetPeersMessage

func NewGetPeersMessage() *GetPeersMessage

NewGetPeersMessage creates GetPeersMessage

func (*GetPeersMessage) Handle

func (gpm *GetPeersMessage) Handle(mc *gnet.MessageContext,
	daemon interface{}) error

Handle handles message

func (*GetPeersMessage) Process

func (gpm *GetPeersMessage) Process(d *Daemon)

Process Notifies the Pex instance that peers were requested

type GetTxnsMessage

type GetTxnsMessage struct {
	Txns []cipher.SHA256
	// contains filtered or unexported fields
}

GetTxnsMessage request transactions of given hash

func NewGetTxnsMessage

func NewGetTxnsMessage(txns []cipher.SHA256) *GetTxnsMessage

NewGetTxnsMessage creates GetTxnsMessage

func (*GetTxnsMessage) Handle

func (gtm *GetTxnsMessage) Handle(mc *gnet.MessageContext, daemon interface{}) error

Handle handle message

func (*GetTxnsMessage) Process

func (gtm *GetTxnsMessage) Process(d *Daemon)

Process process message

type GiveBlocksMessage

type GiveBlocksMessage struct {
	Blocks []coin.SignedBlock
	// contains filtered or unexported fields
}

GiveBlocksMessage sent in response to GetBlocksMessage, or unsolicited

func NewGiveBlocksMessage

func NewGiveBlocksMessage(blocks []coin.SignedBlock) *GiveBlocksMessage

NewGiveBlocksMessage creates GiveBlocksMessage

func (*GiveBlocksMessage) Handle

func (gbm *GiveBlocksMessage) Handle(mc *gnet.MessageContext,
	daemon interface{}) error

Handle handle message

func (*GiveBlocksMessage) Process

func (gbm *GiveBlocksMessage) Process(d *Daemon)

Process process message

type GivePeersMessage

type GivePeersMessage struct {
	Peers []IPAddr
	// contains filtered or unexported fields
}

GivePeersMessage sent in response to GetPeersMessage

func NewGivePeersMessage

func NewGivePeersMessage(peers []pex.Peer) *GivePeersMessage

NewGivePeersMessage []*pex.Peer is converted to []IPAddr for binary transmission

func (*GivePeersMessage) GetPeers

func (gpm *GivePeersMessage) GetPeers() []string

GetPeers is required by the pex.GivePeersMessage interface. It returns the peers contained in the message as an array of "ip:port" strings.

func (*GivePeersMessage) Handle

func (gpm *GivePeersMessage) Handle(mc *gnet.MessageContext, daemon interface{}) error

Handle handle message

func (*GivePeersMessage) Process

func (gpm *GivePeersMessage) Process(d *Daemon)

Process Notifies the Pex instance that peers were received

type GiveTxnsMessage

type GiveTxnsMessage struct {
	Txns coin.Transactions
	// contains filtered or unexported fields
}

GiveTxnsMessage tells the transaction of given hashes

func NewGiveTxnsMessage

func NewGiveTxnsMessage(txns coin.Transactions) *GiveTxnsMessage

NewGiveTxnsMessage creates GiveTxnsMessage

func (*GiveTxnsMessage) GetTxns

func (gtm *GiveTxnsMessage) GetTxns() []cipher.SHA256

GetTxns returns transactions hashes

func (*GiveTxnsMessage) Handle

func (gtm *GiveTxnsMessage) Handle(mc *gnet.MessageContext,
	daemon interface{}) error

Handle handle message

func (*GiveTxnsMessage) Process

func (gtm *GiveTxnsMessage) Process(d *Daemon)

Process process message

type Health

type Health struct {
	BlockchainMetadata *visor.BlockchainMetadata
	Version            visor.BuildInfo
	OpenConnections    int
	Uptime             time.Duration
}

Health is returned by the /health endpoint

type IPAddr

type IPAddr struct {
	IP   uint32
	Port uint16
}

IPAddr compact representation of IP:Port

func NewIPAddr

func NewIPAddr(addr string) (ipaddr IPAddr, err error)

NewIPAddr returns an IPAddr from an ip:port string. If ipv6 or invalid, error is returned

func (IPAddr) String

func (ipa IPAddr) String() string

String returns IPAddr as "ip:port"

type IPCount

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

IPCount records connection number from the same base ip

func NewIPCount

func NewIPCount() *IPCount

NewIPCount returns IPCount instance

func (*IPCount) Decrease

func (ic *IPCount) Decrease(ip string)

Decrease decreases one for specific ip

func (*IPCount) Get

func (ic *IPCount) Get(ip string) (int, bool)

Get return ip count

func (*IPCount) Increase

func (ic *IPCount) Increase(ip string)

Increase increases one for specific ip

type IntroductionMessage

type IntroductionMessage struct {
	// Mirror is a random value generated on client startup that is used
	// to identify self-connections
	Mirror uint32
	// Port is the port that this client is listening on
	Port uint16
	// Our client version
	Version int32
	// contains filtered or unexported fields
}

IntroductionMessage jan IntroductionMessage is sent on first connect by both parties

func NewIntroductionMessage

func NewIntroductionMessage(mirror uint32, version int32, port uint16) *IntroductionMessage

NewIntroductionMessage creates introduction message

func (*IntroductionMessage) Handle

func (intro *IntroductionMessage) Handle(mc *gnet.MessageContext, daemon interface{}) error

Handle Responds to an gnet.Pool event. We implement Handle() here because we need to control the DisconnectReason sent back to gnet. We still implement Process(), where we do modifications that are not threadsafe

func (*IntroductionMessage) Process

func (intro *IntroductionMessage) Process(d *Daemon)

Process an event queued by Handle()

type MessageConfig

type MessageConfig struct {
	Prefix  gnet.MessagePrefix
	Message interface{}
}

MessageConfig config contains a gnet.Message's 4byte prefix and a reference interface

func NewMessageConfig

func NewMessageConfig(prefix string, m interface{}) MessageConfig

NewMessageConfig creates message config

type MessageEvent

type MessageEvent struct {
	Message AsyncMessage
	Context *gnet.MessageContext
}

MessageEvent encapsulates a deserialized message from the network

type Messages

type Messages struct {
	Config MessagesConfig
	// Magic value for detecting self-connection
	Mirror uint32
}

Messages messages struct

func NewMessages

func NewMessages(c MessagesConfig) *Messages

NewMessages creates Messages

type MessagesConfig

type MessagesConfig struct {
	// Message ID prefices
	Messages []MessageConfig
}

MessagesConfig slice of MessageConfig

func NewMessagesConfig

func NewMessagesConfig() MessagesConfig

NewMessagesConfig creates messages config

func (*MessagesConfig) Register

func (msc *MessagesConfig) Register()

Register registers our Messages with gnet

type MirrorConnections

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

MirrorConnections records mirror connections

func NewMirrorConnections

func NewMirrorConnections() *MirrorConnections

NewMirrorConnections create mirror connection instance

func (*MirrorConnections) Add

func (mc *MirrorConnections) Add(mirror uint32, ip string, port uint16)

Add adds mirror connection

func (*MirrorConnections) Get

func (mc *MirrorConnections) Get(mirror uint32, ip string) (uint16, bool)

Get returns ip port of specific mirror

func (*MirrorConnections) Remove

func (mc *MirrorConnections) Remove(mirror uint32, ip string)

Remove removes port of ip for specific mirror

type OutgoingConnections

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

OutgoingConnections records the outgoing connections

func NewOutgoingConnections

func NewOutgoingConnections(max int) *OutgoingConnections

NewOutgoingConnections create OutgoingConnection instance

func (*OutgoingConnections) Add

func (oc *OutgoingConnections) Add(addr string)

Add records connection

func (*OutgoingConnections) Get

func (oc *OutgoingConnections) Get(addr string) bool

Get returns if connection is outgoing

func (*OutgoingConnections) Len

func (oc *OutgoingConnections) Len() int

Len returns the outgoing connections count

func (*OutgoingConnections) Remove

func (oc *OutgoingConnections) Remove(addr string)

Remove remove connection

type OutputsFilter

type OutputsFilter func(outputs coin.UxArray) coin.UxArray

OutputsFilter used as optional arguments in GetUnspentOutputs method

func FbyAddresses

func FbyAddresses(addrs []string) OutputsFilter

FbyAddresses filters the unspent outputs that owned by the addresses

func FbyAddressesNotIncluded

func FbyAddressesNotIncluded(addrs []string) OutputsFilter

FbyAddressesNotIncluded filters the unspent outputs that are not owned by the addresses

func FbyHashes

func FbyHashes(hashes []string) OutputsFilter

FbyHashes filters the unspent outputs that have hashes matched.

type PeerBlockchainHeight

type PeerBlockchainHeight struct {
	Address string
	Height  uint64
}

PeerBlockchainHeight is a peer's IP address with their reported blockchain height

type PendingConnections

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

PendingConnections records pending connection peers

func NewPendingConnections

func NewPendingConnections(maxConn int) *PendingConnections

NewPendingConnections creates new PendingConnections instance

func (*PendingConnections) Add

func (pc *PendingConnections) Add(addr string, peer pex.Peer)

Add adds pending connection

func (*PendingConnections) Get

func (pc *PendingConnections) Get(addr string) (pex.Peer, bool)

Get returns pending connections

func (*PendingConnections) Len

func (pc *PendingConnections) Len() int

Len returns pending connection number

func (*PendingConnections) Remove

func (pc *PendingConnections) Remove(addr string)

Remove removes pending connection

type PingMessage

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

PingMessage Sent to keep a connection alive. A PongMessage is sent in reply.

func (*PingMessage) Handle

func (ping *PingMessage) Handle(mc *gnet.MessageContext, daemon interface{}) error

Handle implements the Messager interface

func (*PingMessage) Process

func (ping *PingMessage) Process(d *Daemon)

Process Sends a PongMessage to the sender of PingMessage

type PongMessage

type PongMessage struct {
}

PongMessage Sent in reply to a PingMessage. No action is taken when this is received.

func (*PongMessage) Handle

func (pong *PongMessage) Handle(mc *gnet.MessageContext, daemon interface{}) error

Handle handles message

type Pool

type Pool struct {
	Config PoolConfig
	Pool   *gnet.ConnectionPool
}

Pool maintains config and pool

func NewPool

func NewPool(c PoolConfig, d *Daemon) *Pool

NewPool creates pool

func (*Pool) Run

func (pool *Pool) Run() error

Run starts listening on the configured Port

func (*Pool) RunOffline

func (pool *Pool) RunOffline() error

RunOffline runs the pool without a listener. This is necessary to process strand requests.

func (*Pool) Shutdown

func (pool *Pool) Shutdown()

Shutdown closes all connections and stops listening

type PoolConfig

type PoolConfig struct {
	// Timeout when trying to connect to new peers through the pool
	DialTimeout time.Duration
	// How often to process message buffers and generate events
	MessageHandlingRate time.Duration
	// How long to wait before sending another ping
	PingRate time.Duration
	// How long a connection can idle before considered stale
	IdleLimit time.Duration
	// How often to check for needed pings
	IdleCheckRate time.Duration
	// How often to check for stale connections
	ClearStaleRate time.Duration
	// Buffer size for gnet.ConnectionPool's network Read events
	EventChannelSize int
	// contains filtered or unexported fields
}

PoolConfig pool config

func NewPoolConfig

func NewPoolConfig() PoolConfig

NewPoolConfig creates pool config

type RPC

type RPC struct{}

RPC rpc

func (RPC) GetAllExchgConnections

func (rpc RPC) GetAllExchgConnections(d *Daemon) []string

GetAllExchgConnections return all exchangeable connections

func (RPC) GetBlockchainProgress

func (rpc RPC) GetBlockchainProgress(v *Visor) *BlockchainProgress

GetBlockchainProgress gets the blockchain progress

func (RPC) GetConnection

func (rpc RPC) GetConnection(d *Daemon, addr string) *Connection

GetConnection gets connection of given address

func (RPC) GetConnections

func (rpc RPC) GetConnections(d *Daemon) *Connections

GetConnections gets all connections

func (RPC) GetDefaultConnections

func (rpc RPC) GetDefaultConnections(d *Daemon) []string

GetDefaultConnections gets default connections

func (RPC) GetTrustConnections

func (rpc RPC) GetTrustConnections(d *Daemon) []string

GetTrustConnections get all trusted transaction

func (RPC) ResendTransaction

func (rpc RPC) ResendTransaction(v *Visor, p *Pool, txHash cipher.SHA256) *ResendResult

ResendTransaction rebroadcast transaction

func (RPC) ResendUnconfirmedTxns

func (rpc RPC) ResendUnconfirmedTxns(v *Visor, p *Pool) *ResendResult

ResendUnconfirmedTxns rebroadcast unconfirmed transactions

type ResendResult

type ResendResult struct {
	Txids []string `json:"txids"` // transaction id
}

ResendResult rebroadcast tx result

type SendingTxnsMessage

type SendingTxnsMessage interface {
	GetTxns() []cipher.SHA256
}

SendingTxnsMessage send transaction message interface

type Visor

type Visor struct {
	Config VisorConfig
	// contains filtered or unexported fields
}

Visor struct

func NewVisor

func NewVisor(c VisorConfig, db *bolt.DB) (*Visor, error)

NewVisor creates visor instance

func (*Visor) AnnounceAllTxns

func (vs *Visor) AnnounceAllTxns(pool *Pool) error

AnnounceAllTxns announces local unconfirmed transactions

func (*Visor) AnnounceBlocks

func (vs *Visor) AnnounceBlocks(pool *Pool) error

AnnounceBlocks sends an AnnounceBlocksMessage to all connections

func (*Visor) AnnounceTxns

func (vs *Visor) AnnounceTxns(pool *Pool, txns []cipher.SHA256) error

AnnounceTxns announces given transaction hashes.

func (*Visor) CreateAndPublishBlock

func (vs *Visor) CreateAndPublishBlock(pool *Pool) (coin.SignedBlock, error)

CreateAndPublishBlock creates a block from unconfirmed transactions and sends it to the network. Will panic if not running as a master chain. Returns creation error and whether it was published or not

func (*Visor) EstimateBlockchainHeight

func (vs *Visor) EstimateBlockchainHeight() uint64

EstimateBlockchainHeight returns the blockchain length estimated from peer reports Deprecate. Should not need. Just report time of last block

func (*Visor) ExecuteSignedBlock

func (vs *Visor) ExecuteSignedBlock(b coin.SignedBlock) error

ExecuteSignedBlock executes signed block

func (*Visor) GetPeerBlockchainHeights

func (vs *Visor) GetPeerBlockchainHeights() []PeerBlockchainHeight

GetPeerBlockchainHeights returns recorded peers' blockchain heights as an array.

func (*Visor) GetSignedBlock

func (vs *Visor) GetSignedBlock(seq uint64) (*coin.SignedBlock, error)

GetSignedBlock returns a copy of signed block at seq. Returns error if seq is greater than blockhain height.

func (*Visor) GetSignedBlocksSince

func (vs *Visor) GetSignedBlocksSince(seq uint64, ct uint64) ([]coin.SignedBlock, error)

GetSignedBlocksSince returns signed blocks in an inclusive range of [seq+1, seq+ct]

func (*Visor) HeadBkSeq

func (vs *Visor) HeadBkSeq() uint64

HeadBkSeq returns the head sequence

func (*Visor) InjectBroadcastTransaction

func (vs *Visor) InjectBroadcastTransaction(txn coin.Transaction, pool *Pool) error

InjectBroadcastTransaction injects transaction to the unconfirmed pool and broadcasts it. If the transaction violates either hard or soft constraints, it is not broadcast. This method is to be used by user-initiated transaction injections. For transactions received over the network, use InjectTransaction and check the result to decide on repropagation.

func (*Visor) InjectTransaction

func (vs *Visor) InjectTransaction(tx coin.Transaction) (bool, *visor.ErrTxnViolatesSoftConstraint, error)

InjectTransaction adds a transaction to the unconfirmed txn pool if it does not violate hard constraints. The transaction is added to the pool if it only violates soft constraints. If a soft constraint is violated, the specific error is returned separately.

func (*Visor) RecordBlockchainHeight

func (vs *Visor) RecordBlockchainHeight(addr string, bkLen uint64)

RecordBlockchainHeight saves a peer-reported blockchain length

func (*Visor) RefreshUnconfirmed

func (vs *Visor) RefreshUnconfirmed() ([]cipher.SHA256, error)

RefreshUnconfirmed checks unconfirmed txns against the blockchain and marks and returns those that become valid

func (*Visor) RemoveConnection

func (vs *Visor) RemoveConnection(addr string)

RemoveConnection updates internal state when a connection disconnects

func (*Visor) RemoveInvalidUnconfirmed

func (vs *Visor) RemoveInvalidUnconfirmed() ([]cipher.SHA256, error)

RemoveInvalidUnconfirmed checks unconfirmed txns against the blockchain and purges those that become permanently invalid, violating hard constraints

func (*Visor) RequestBlocks

func (vs *Visor) RequestBlocks(pool *Pool) error

RequestBlocks Sends a GetBlocksMessage to all connections

func (*Visor) RequestBlocksFromAddr

func (vs *Visor) RequestBlocksFromAddr(pool *Pool, addr string) error

RequestBlocksFromAddr sends a GetBlocksMessage to one connected address

func (*Visor) ResendTransaction

func (vs *Visor) ResendTransaction(h cipher.SHA256, pool *Pool) error

ResendTransaction resends a known UnconfirmedTxn.

func (*Visor) ResendUnconfirmedTxns

func (vs *Visor) ResendUnconfirmedTxns(pool *Pool) []cipher.SHA256

ResendUnconfirmedTxns resents all unconfirmed transactions

func (*Visor) Run

func (vs *Visor) Run() error

Run starts the visor

func (*Visor) SetTxnsAnnounced

func (vs *Visor) SetTxnsAnnounced(txns []cipher.SHA256)

SetTxnsAnnounced sets all txns as announced

func (*Visor) Shutdown

func (vs *Visor) Shutdown()

Shutdown shuts down the visor

func (*Visor) UnConfirmFilterKnown

func (vs *Visor) UnConfirmFilterKnown(txns []cipher.SHA256) []cipher.SHA256

UnConfirmFilterKnown returns all unknown transaction hashes

func (*Visor) UnConfirmKnow

func (vs *Visor) UnConfirmKnow(hashes []cipher.SHA256) coin.Transactions

UnConfirmKnow returns all know tansactions

type VisorConfig

type VisorConfig struct {
	Config visor.Config
	// Disable visor networking
	DisableNetworking bool
	// How often to request blocks from peers
	BlocksRequestRate time.Duration
	// How often to announce our blocks to peers
	BlocksAnnounceRate time.Duration
	// How many blocks to respond with to a GetBlocksMessage
	BlocksResponseCount uint64
	// How long between saving copies of the blockchain
	BlockchainBackupRate time.Duration
	// Max announce txns hash number
	MaxTxnAnnounceNum int
	// How often to announce our unconfirmed txns to peers
	TxnsAnnounceRate time.Duration
	// How long to wait for Visor request to process
	RequestDeadline time.Duration
	// Internal request buffer size
	RequestBufferSize int
}

VisorConfig represents the configuration of visor

func NewVisorConfig

func NewVisorConfig() VisorConfig

NewVisorConfig creates default visor config

Directories

Path Synopsis
Package pex is a toolkit for implementing a peer exchange system
Package pex is a toolkit for implementing a peer exchange system

Jump to

Keyboard shortcuts

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