p2p

package
v0.3.13 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2021 License: ISC Imports: 34 Imported by: 0

Documentation

Overview

Copyright (c) 2020 The JaxNetwork developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2020 The JaxNetwork developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2020 The JaxNetwork developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2020 The JaxNetwork developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2020 The JaxNetwork developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Copyright (c) 2020 The JaxNetwork developers Use of this source code is governed by an ISC license that can be found in the LICENSE file.

Upnp code taken from Taipei Torrent license is below: Copyright (c) 2010 Jack Palevich. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright

notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above

copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  • Neither the name of Google Inc. nor the names of its

contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetFreePort

func GetFreePort() (port int, err error)

func GetFreePortList

func GetFreePortList(count int) (ports []int, err error)

func ParseListeners

func ParseListeners(addrs []string) ([]net.Addr, error)

ParseListeners determines whether each listen address is IPv4 and IPv6 and returns a slice of appropriate net.Addrs to listen on with TCP. It also properly detects addresses which apply to "all interfaces" and adds the address as both IPv4 and IPv6.

func SetPortForListeners

func SetPortForListeners(listeners []string, port int) []string

Types

type ChainPort

type ChainPort struct {
	ShardID uint32
	Port    int
	NetName string
}

type ChainsPortIndex

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

func NewPortsIndex

func NewPortsIndex() *ChainsPortIndex

func (*ChainsPortIndex) Add

func (ind *ChainsPortIndex) Add(shardID uint32, port int)

func (*ChainsPortIndex) Delete

func (ind *ChainsPortIndex) Delete(shardID uint32)

func (*ChainsPortIndex) Get

func (ind *ChainsPortIndex) Get(shardID uint32) (int, bool)

type Config

type Config struct {
	Peers          []string `yaml:"peers" toml:"peers" `
	Listeners      []string `yaml:"listeners" toml:"listeners"`
	AgentBlacklist []string `yaml:"agent_blacklist" toml:"agent_blacklist"`
	AgentWhitelist []string `yaml:"agent_whitelist" toml:"agent_whitelist"`
	DisableListen  bool     `` /* 261-byte string literal not displayed */

	ExternalIPs    []string      `` /* 143-byte string literal not displayed */
	ConnectPeers   []string      `yaml:"connect_peers" toml:"connect_peers" long:"connect" description:"Connect only to the specified peers at startup"`
	BanDuration    time.Duration `` /* 158-byte string literal not displayed */
	BanThreshold   uint32        `` /* 153-byte string literal not displayed */
	DisableBanning bool          `yaml:"disable_banning" toml:"disable_banning" long:"nobanning" description:"Disable banning of misbehaving peers"`
	BlocksOnly     bool          `yaml:"blocks_only" toml:"blocks_only" long:"blocksonly" description:"Do not accept transactions from remote peers."`

	DisableOutbound    bool          `yaml:"disable_outbound" toml:"disable_outbound"`
	DisableTLS         bool          `` /* 165-byte string literal not displayed */
	OnionProxy         string        `` /* 133-byte string literal not displayed */
	OnionProxyPass     string        `` /* 127-byte string literal not displayed */
	OnionProxyUser     string        `yaml:"onion_proxy_user" toml:"onion_proxy_user" long:"onionuser" description:"Username for onion proxy Server"`
	Proxy              string        `yaml:"proxy" toml:"proxy" long:"proxy" description:"Connect via SOCKS5 proxy (eg. 127.0.0.1:9050)"`
	ProxyPass          string        `yaml:"proxy_pass" toml:"proxy_pass" long:"proxypass" default-mask:"-" description:"Password for proxy Server"`
	ProxyUser          string        `yaml:"proxy_user" toml:"proxy_user" long:"proxyuser" description:"Username for proxy Server"`
	RejectNonStd       bool          `` /* 169-byte string literal not displayed */
	TrickleInterval    time.Duration `` /* 158-byte string literal not displayed */
	DisableDNSSeed     bool          `yaml:"disable_dns_seed" toml:"disable_dns_seed" long:"nodnsseed" description:"Disable DNS seeding for peers"`
	NoOnion            bool          `yaml:"no_onion" toml:"no_onion" long:"noonion" description:"Disable connecting to tor hidden services"`
	NoPeerBloomFilters bool          `long:"nopeerbloomfilters" description:"Disable bloom filtering support"`
	Upnp               bool          `yaml:"upnp" toml:"upnp" long:"upnp" description:"Use UPnP to map our listening port outside of NAT"`
	ShardDefaultPort   int           `yaml:"shard_default_port" toml:"shard_default_port" long:"sharddefaultport"`

	Oniondial    func(string, string, time.Duration) (net.Conn, error) `toml:"-" yaml:"-"`
	Dial         func(string, string, time.Duration) (net.Conn, error) `toml:"-" yaml:"-"`
	Lookup       func(string) ([]net.IP, error)                        `toml:"-" yaml:"-"`
	GetChainPort func(shardID uint32) (int, bool)                      `toml:"-" yaml:"-"`
}

type ConnManager

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

ConnManager provides a connection manager for use with the RPC Server and implements the P2PConnManager interface.

func (*ConnManager) AddRebroadcastInventory

func (cm *ConnManager) AddRebroadcastInventory(iv *types.InvVect, data interface{})

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 P2PConnManager interface implementation.

func (*ConnManager) BroadcastMessage

func (cm *ConnManager) BroadcastMessage(msg wire.Message)

BroadcastMessage sends the provided message to all currently connected peers.

This function is safe for concurrent access and is part of the P2PConnManager interface implementation.

func (*ConnManager) Connect

func (cm *ConnManager) Connect(addr string, permanent bool) error

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 P2PConnManager interface implementation.

func (*ConnManager) ConnectedCount

func (cm *ConnManager) ConnectedCount() int32

ConnectedCount returns the number of currently connected peers.

This function is safe for concurrent access and is part of the P2PConnManager interface implementation.

func (*ConnManager) ConnectedPeers

func (cm *ConnManager) ConnectedPeers() []netsync.ServerPeer

ConnectedPeers returns an array consisting of all connected peers.

This function is safe for concurrent access and is part of the P2PConnManager interface implementation.

func (*ConnManager) DisconnectByAddr

func (cm *ConnManager) DisconnectByAddr(addr string) 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.

This function is safe for concurrent access and is part of the P2PConnManager interface implementation.

func (*ConnManager) DisconnectByID

func (cm *ConnManager) DisconnectByID(id int32) 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.

This function is safe for concurrent access and is part of the P2PConnManager interface implementation.

func (*ConnManager) NetTotals

func (cm *ConnManager) NetTotals() (uint64, uint64)

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 P2PConnManager interface implementation.

func (*ConnManager) PersistentPeers

func (cm *ConnManager) PersistentPeers() []netsync.ServerPeer

PersistentPeers returns an array consisting of all the added persistent peers.

This function is safe for concurrent access and is part of the P2PConnManager interface implementation.

func (*ConnManager) RelayTransactions

func (cm *ConnManager) RelayTransactions(txns []*mempool.TxDesc)

RelayTransactions generates and relays inventory vectors for all of the passed transactions to all connected peers.

func (*ConnManager) RemoveByAddr

func (cm *ConnManager) RemoveByAddr(addr string) 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.

This function is safe for concurrent access and is part of the P2PConnManager interface implementation.

func (*ConnManager) RemoveByID

func (cm *ConnManager) RemoveByID(id int32) 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.

This function is safe for concurrent access and is part of the P2PConnManager interface implementation.

type ConnectNodeMsg

type ConnectNodeMsg struct {
	Addr      string
	Permanent bool
	Reply     chan error
}

type DisconnectNodeMsg

type DisconnectNodeMsg struct {
	Cmp   func(*serverPeer) bool
	Reply chan error
}

type GetAddedNodesMsg

type GetAddedNodesMsg struct {
	Reply chan []*serverPeer
}

type GetConnCountMsg

type GetConnCountMsg struct {
	Reply chan int32
}

type GetOutboundGroup

type GetOutboundGroup struct {
	Key   string
	Reply chan int
}

type GetPeerStatsMsg

type GetPeerStatsMsg struct {
	Reply chan PeerStateStats
}

type GetPeersMsg

type GetPeersMsg struct {
	Reply chan []*serverPeer
}

type INodeServer

type INodeServer interface {
	Start()
	Stop() error
	NotifyNewTransactions(txns []*mempool.TxDesc)
}

type ListenOpts

type ListenOpts struct {
	DefaultPort int
	Listeners   []string
}

func (*ListenOpts) Update

func (o *ListenOpts) Update(listeners []string, chainID uint32, shardDefaultPort int) (err error)

type NAT

type NAT interface {
	// Get the external address from outside the NAT.
	GetExternalAddress() (addr net.IP, err error)
	// 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)
	// 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 PeerStateStats

type PeerStateStats struct {
	Total           int
	InboundPeers    int
	OutboundPeers   int
	PersistentPeers int
	Banned          int
	OutboundGroups  int
}

type PeersConfig

type PeersConfig struct {
	DisableBanning  bool          `yaml:"disable_banning" toml:"disable_banning" long:"nobanning" description:"Disable banning of misbehaving peers"`
	BanThreshold    uint32        `` /* 153-byte string literal not displayed */
	BlocksOnly      bool          `yaml:"blocks_only" toml:"blocks_only" long:"blocksonly" description:"Do not accept transactions from remote peers."`
	Proxy           string        `yaml:"proxy" toml:"proxy" long:"proxy" description:"Connect via SOCKS5 proxy (eg. 127.0.0.1:9050)"`
	TrickleInterval time.Duration `` /* 158-byte string literal not displayed */
}

type RelayMsg

type RelayMsg struct {
	InvVect *types.InvVect
	Data    interface{}
}

RelayMsg packages an inventory vector along with the newly discovered inventory so the relay has access to that information.

type RemoveNodeMsg

type RemoveNodeMsg struct {
	Cmp   func(*serverPeer) bool
	Reply chan error
}

type Server

type Server struct {
	ConnManager *connmgr.ConnManager
	// contains filtered or unexported fields
}

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

func NewServer

func NewServer(cfg *Config, chainProvider *cprovider.ChainProvider,
	amgr *addrmgr.AddrManager, opts ListenOpts) (*Server, error)

NewServer returns a new jaxnetd p2p server configured to listen on addr for the bitcoin network type specified by ChainParams. Use start to begin accepting connections from peers.

func (*Server) AddBytesReceived

func (server *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 (server *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) AddRebroadcastInventory

func (server *Server) AddRebroadcastInventory(iv *types.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 (server *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) BroadcastMessage

func (server *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 (server *Server) ConnectedCount() int32

ConnectedCount returns the number of currently connected peers.

func (*Server) NetTotals

func (server *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 (server *Server) OutboundGroupCount(key string) int

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

func (*Server) P2PConnManager

func (server *Server) P2PConnManager() netsync.P2PConnManager

func (*Server) PeerStateStats

func (server *Server) PeerStateStats() PeerStateStats

ConnectedCount returns the number of currently connected peers.

func (*Server) Query

func (server *Server) Query(value interface{})

func (*Server) RelayInventory

func (server *Server) RelayInventory(invVect *types.InvVect, data interface{})

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

func (*Server) RelayTransactions

func (server *Server) RelayTransactions(txns []*mempool.TxDesc)

RelayTransactions generates and relays inventory vectors for all of the passed transactions to all connected peers.

func (*Server) RemoveRebroadcastInventory

func (server *Server) RemoveRebroadcastInventory(iv *types.InvVect)

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

func (*Server) Run

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

func (*Server) ScheduleShutdown

func (server *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) Stop

func (server *Server) Stop() error

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

func (*Server) TransactionConfirmed

func (server *Server) TransactionConfirmed(tx *jaxutil.Tx)

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

func (*Server) UpdatePeerHeights

func (server *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 BlockChain 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 (server *Server) WaitForShutdown()

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

type UpdatePeerHeightsMsg

type UpdatePeerHeightsMsg struct {
	NewHash    *chainhash.Hash
	NewHeight  int32
	OriginPeer *peer.Peer
}

UpdatePeerHeightsMsg is a message sent from the blockmanager to the server after a new block has been accepted. The purpose of the message is to update the heights of peers that were known to announce the block before we connected it to the main BlockChain or recognized it as an orphan. With these updates, peer heights will be kept up to date, allowing for fresh data when selecting sync peer candidacy.

Jump to

Keyboard shortcuts

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