Help us shape the future of Go! Take the 2026 Go Developer Survey

p2p

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2019 License: MIT Imports: 43 Imported by: 0

Documentation

Overview

Package p2p TODO add package documentation

Index

Constants

View Source
const (
	PeriodTime = 2 * 60

	PingBody = "ping"
	PongBody = "pong"

	// [Low, Mid, High, Top]
	PriorityMsgTypeSize = 4
	PriorityQueueCap    = 65536
)

const

View Source
const (
	// ConnMaxCapacity means the max capacity of the conn pool
	ConnMaxCapacity = 200

	// ConnLoadFactor means the threshold of gc
	ConnLoadFactor = 0.8
)
View Source
const (
	ProtocolID = "/box/1.0.0"
	// Mainnet velocity of light
	Mainnet         uint32 = 0x11de784a
	Testnet         uint32 = 0x54455354
	FixHeaderLength        = 4

	// dont forget to set messageAttribute below
	Ping              uint32 = 0x00
	Pong              uint32 = 0x01
	PeerDiscover      uint32 = 0x02
	PeerDiscoverReply uint32 = 0x03
	NewBlockMsg       uint32 = 0x04
	TransactionMsg    uint32 = 0x05

	// Sync Manager
	LocateForkPointRequest  = 0x10
	LocateForkPointResponse = 0x11
	LocateCheckRequest      = 0x12
	LocateCheckResponse     = 0x13
	BlockChunkRequest       = 0x14
	BlockChunkResponse      = 0x15

	LightSyncRequest = 0x17
	LightSyncReponse = 0x18

	BlockPrepareMsg = 0x19
	BlockCommitMsg  = 0x20

	MaxMessageDataLength = 1024 * 1024 * 1024 // 1GB
)

const

View Source
const (
	PeerDiscoverLoopInterval        = 120 * 1000
	MaxPeerCountToSyncRouteTable    = 16
	MaxPeerCountToReplyPeerDiscover = 16
)

const

Variables

View Source
var (
	//conn.go
	ErrMagic                     = errors.New("magic is error")
	ErrHeaderCheckSum            = errors.New("header checksum is error")
	ErrExceedMaxDataLength       = errors.New("exceed max data length")
	ErrBodyCheckSum              = errors.New("body checksum is error")
	ErrMessageDataContent        = errors.New("Invalid message data content")
	ErrNoConnectionEstablished   = errors.New("No connection established")
	ErrFailedToSendMessageToPeer = errors.New("Failed to send message to peer")
	ErrDuplicateMessage          = errors.New("Duplicate message")

	//message.go
	ErrMessageHeaderLength     = errors.New("Can not read p2p message header length")
	ErrMessageHeader           = errors.New("Invalid p2p message header data")
	ErrMessageDataBody         = errors.New("Invalid p2p message body")
	ErrFromProtoMessageMessage = errors.New("Invalid proto message")
	ErrNoNeedToRelay           = errors.New("Message no need to relay")
)

error defined

View Source
var NetworkNameToMagic = map[string]uint32{
	"mainnet": Mainnet,
	"testnet": Testnet,
}

NetworkNameToMagic is a map from network name to magic number.

Functions

func DecapsulatePeerMultiAddr

func DecapsulatePeerMultiAddr(addr ma.Multiaddr) (ma.Multiaddr, peer.ID, error)

DecapsulatePeerMultiAddr decapsulates a p2p multiaddr into host multiaddr and peer id e.g. /ip4/192.168.10.34/tcp/19199/p2p/12D3KooWLornEge5BiVbL92o8wdFivY4c7GV3QdfmjkFk7Vm48Uk decapsuated to /ip4/192.168.10.34/tcp/19199, 12D3KooWLornEge5BiVbL92o8wdFivY4c7GV3QdfmjkFk7Vm48Uk

func EncapsulatePeerMultiAddr

func EncapsulatePeerMultiAddr(addr ma.Multiaddr, peerid peer.ID) (ma.Multiaddr, error)

EncapsulatePeerMultiAddr encapsulates a host multiaddr and peer id into p2p multiaddr e.g. /ip4/192.168.10.34/tcp/19199 and 12D3KooWLornEge5BiVbL92o8wdFivY4c7GV3QdfmjkFk7Vm48Uk encapsuated to /ip4/192.168.10.34/tcp/19199/p2p/12D3KooWLornEge5BiVbL92o8wdFivY4c7GV3QdfmjkFk7Vm48Uk

func PeerMultiAddr

func PeerMultiAddr(h host.Host) (ma.Multiaddr, error)

PeerMultiAddr returns the full p2p multiaddr of specified host. e.g. /ip4/192.168.10.34/tcp/19199/p2p/12D3KooWLornEge5BiVbL92o8wdFivY4c7GV3QdfmjkFk7Vm48Uk

func UpdateSynced

func UpdateSynced(synced bool)

UpdateSynced update peers' isSynced

Types

type BoxPeer

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

BoxPeer represents a connected remote node.

func NewBoxPeer

func NewBoxPeer(parent goprocess.Process, config *Config, s storage.Storage, bus eventbus.Bus) (*BoxPeer, error)

NewBoxPeer create a BoxPeer

func (*BoxPeer) AddAddrToPeerstore

func (p *BoxPeer) AddAddrToPeerstore(addr string) error

AddAddrToPeerstore adds specified address to peerstore

func (*BoxPeer) AddToPeerstore

func (p *BoxPeer) AddToPeerstore(maddr multiaddr.Multiaddr) error

AddToPeerstore adds specified multiaddr to peerstore

func (*BoxPeer) Broadcast

func (p *BoxPeer) Broadcast(code uint32, msg conv.Convertible) error

Broadcast business message.

func (*BoxPeer) BroadcastToBookkeepers added in v0.5.0

func (p *BoxPeer) BroadcastToBookkeepers(code uint32, msg conv.Convertible, bookkeepers []string) error

BroadcastToBookkeepers business message to bookkeepers.

func (*BoxPeer) Conns

func (p *BoxPeer) Conns() *sync.Map

Conns return peer connections.

func (*BoxPeer) Notify

func (p *BoxPeer) Notify(msg Message)

Notify publishes a message notification.

func (*BoxPeer) PeerSynced

func (p *BoxPeer) PeerSynced(peerID peer.ID) (bool, bool)

PeerSynced get sync states of remote peers

func (*BoxPeer) PickOnePeer

func (p *BoxPeer) PickOnePeer(peersExclusive ...peer.ID) peer.ID

PickOnePeer picks a peer not in peersExclusive and return its id

func (*BoxPeer) Proc

func (p *BoxPeer) Proc() goprocess.Process

Proc returns the gopreocess of database

func (*BoxPeer) Relay added in v0.3.0

func (p *BoxPeer) Relay(code uint32, msg conv.Convertible) error

Relay business message.

func (*BoxPeer) Run

func (p *BoxPeer) Run() error

Run schedules lookup and discover new peer

func (*BoxPeer) SendMessageToPeer

func (p *BoxPeer) SendMessageToPeer(code uint32, msg conv.Convertible, pid peer.ID) error

SendMessageToPeer sends message to a peer.

func (*BoxPeer) Stop

func (p *BoxPeer) Stop()

Stop box peer service

func (*BoxPeer) Subscribe

func (p *BoxPeer) Subscribe(notifiee *Notifiee)

Subscribe a message notification.

func (*BoxPeer) UnSubscribe

func (p *BoxPeer) UnSubscribe(notifiee *Notifiee)

UnSubscribe cancel subcribe.

type Config

type Config struct {
	Magic           uint32        `mapstructure:"magic"`
	KeyPath         string        `mapstructure:"key_path"`
	Port            uint32        `mapstructure:"port"`
	Address         string        `mapstructure:"address"`
	Seeds           []string      `mapstructure:"seeds"`
	Bucketsize      int           `mapstructure:"bucket_size"`
	Latency         time.Duration `mapstructure:"latency"`
	AddPeers        []string      `mapstructure:"addpeer"`
	ConnMaxCapacity uint32        `mapstructure:"conn_max_capacity"`
	ConnLoadFactor  float32       `mapstructure:"conn_load_factor"`
	RelaySize       uint32        `mapstructure:"relay_size"`
}

Config for peer configuration

type Conn

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

Conn represents a connection to a remote node

func NewConn

func NewConn(stream libp2pnet.Stream, peer *BoxPeer, peerID peer.ID) *Conn

NewConn create a stream to remote peer.

func (*Conn) Close

func (conn *Conn) Close() error

Close connection to remote peer.

func (*Conn) Establish

func (conn *Conn) Establish() bool

Establish means establishing the connection. It returns the previous status.

func (*Conn) Established

func (conn *Conn) Established() bool

Established returns whether the connection is established.

func (*Conn) Handle

func (conn *Conn) Handle(msg *remoteMessage) error

Handle is called on loop

func (*Conn) Loop

func (conn *Conn) Loop(parent goprocess.Process)

Loop start

func (*Conn) OnPeerDiscover

func (conn *Conn) OnPeerDiscover(body []byte) error

OnPeerDiscover handle PeerDiscover message.

func (*Conn) OnPeerDiscoverReply

func (conn *Conn) OnPeerDiscoverReply(body []byte) error

OnPeerDiscoverReply handle PeerDiscoverReply message.

func (*Conn) OnPing

func (conn *Conn) OnPing(data []byte) error

OnPing respond the ping message

func (*Conn) OnPong

func (conn *Conn) OnPong(data []byte) error

OnPong respond the pong message

func (*Conn) PeerDiscover

func (conn *Conn) PeerDiscover() error

PeerDiscover discover new peers from remoute peer. TODO: we should discover other peers periodly via randomly selected remote active peers. Now we only send peer discovery msg once after connections is established.

func (*Conn) Ping

func (conn *Conn) Ping() error

Ping the target node

func (*Conn) Write

func (conn *Conn) Write(opcode uint32, body []byte) error

type ConnManager

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

ConnManager is an object to maitian all connections

func NewConnManager

func NewConnManager(ps peerstore.Peerstore) *ConnManager

NewConnManager creates a ConnManager object, which is used on Host object.

func (*ConnManager) ClosedStream

func (cm *ConnManager) ClosedStream(network net.Network, stream net.Stream)

ClosedStream is called when a stream closed

func (*ConnManager) Connected

func (cm *ConnManager) Connected(network net.Network, conn net.Conn)

Connected is called when a connection opened

func (*ConnManager) Disconnected

func (cm *ConnManager) Disconnected(network net.Network, conn net.Conn)

Disconnected is called when a connection closed

func (*ConnManager) GetTagInfo

func (cm *ConnManager) GetTagInfo(p peer.ID) *ifconnmgr.TagInfo

GetTagInfo returns the metadata associated with the peer, or nil if no metadata has been recorded for the peer.

func (*ConnManager) Listen

func (cm *ConnManager) Listen(network net.Network, multiaddr ma.Multiaddr)

Listen is called when network starts listening on an addr

func (*ConnManager) ListenClose

func (cm *ConnManager) ListenClose(network net.Network, multiaddr ma.Multiaddr)

ListenClose is called when network starts listening on an addr

func (*ConnManager) Loop

func (cm *ConnManager) Loop(parent goprocess.Process)

Loop starts a go thread to loop removing unnecessary connections.

func (*ConnManager) Notifee

func (cm *ConnManager) Notifee() inet.Notifiee

Notifee returns an implementation that can be called back to inform of opened and closed connections.

func (*ConnManager) OpenedStream

func (cm *ConnManager) OpenedStream(network net.Network, stream net.Stream)

OpenedStream is called when a stream opened

func (*ConnManager) Stop

func (cm *ConnManager) Stop()

Stop function stops the ConnManager

func (*ConnManager) TagPeer

func (cm *ConnManager) TagPeer(p peer.ID, tag string, value int)

TagPeer tags a peer with a string, associating a weight with the tag.

func (*ConnManager) TrimOpenConns

func (cm *ConnManager) TrimOpenConns(ctx context.Context)

TrimOpenConns terminates open connections based on an implementation-defined heuristic.

func (*ConnManager) UntagPeer

func (cm *ConnManager) UntagPeer(p peer.ID, tag string)

UntagPeer removes the tagged value from the peer.

type ConnStatus

type ConnStatus int

ConnStatus represents the connection status

const (
	// ConnStatusTagName is the tag name of ConnStatus
	ConnStatusTagName = "cmgr:status"

	// ConnStatusNotTried means there is no tries to connect with the peer
	ConnStatusNotTried ConnStatus = 0

	// ConnStatusConnected means the peer is connected.
	ConnStatusConnected ConnStatus = 1

	// ConnStatusDisconnected means the peer is disconnected.
	ConnStatusDisconnected ConnStatus = 2
)

func (ConnStatus) String

func (cs ConnStatus) String() string

type DummyPeer

type DummyPeer struct{}

DummyPeer implements Net interface for testing purpose

func NewDummyPeer

func NewDummyPeer() *DummyPeer

NewDummyPeer creates a new DummyPeer

func (*DummyPeer) Broadcast

func (d *DummyPeer) Broadcast(uint32, conv.Convertible) error

Broadcast for testing

func (*DummyPeer) BroadcastToBookkeepers added in v0.5.0

func (d *DummyPeer) BroadcastToBookkeepers(code uint32, msg conv.Convertible, bookkeepers []string) error

BroadcastToBookkeepers broadcast to bookkeepers

func (*DummyPeer) Notify

func (d *DummyPeer) Notify(Message)

Notify for testing

func (*DummyPeer) PeerSynced

func (d *DummyPeer) PeerSynced(peers peer.ID) (bool, bool)

PeerSynced get sync states of remote peers

func (*DummyPeer) PickOnePeer

func (d *DummyPeer) PickOnePeer(...peer.ID) peer.ID

PickOnePeer for testing

func (*DummyPeer) Relay added in v0.3.0

func (d *DummyPeer) Relay(uint32, conv.Convertible) error

Relay for testing

func (*DummyPeer) SendMessageToPeer

func (d *DummyPeer) SendMessageToPeer(uint32, conv.Convertible, peer.ID) error

SendMessageToPeer for testing

func (*DummyPeer) Subscribe

func (d *DummyPeer) Subscribe(*Notifiee)

Subscribe for testing

func (*DummyPeer) UnSubscribe

func (d *DummyPeer) UnSubscribe(*Notifiee)

UnSubscribe for testing

type Message

type Message interface {
	Code() uint32
	Body() []byte
	From() peer.ID
}

Message Define message interface

type Net

type Net interface {
	Broadcast(uint32, conv.Convertible) error
	Relay(uint32, conv.Convertible) error
	SendMessageToPeer(uint32, conv.Convertible, peer.ID) error
	Subscribe(*Notifiee)
	UnSubscribe(*Notifiee)
	Notify(Message)
	PickOnePeer(peersExclusive ...peer.ID) peer.ID
	BroadcastToBookkeepers(uint32, conv.Convertible, []string) error
	PeerSynced(peers peer.ID) (bool, bool)
}

Net Define Net interface

type Notifiee

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

Notifiee represent message receiver.

func NewNotifiee

func NewNotifiee(code uint32, messageCh chan Message) *Notifiee

NewNotifiee return a message notifiee.

type Notifier

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

Notifier dispatcher & distribute business message.

func NewNotifier

func NewNotifier() *Notifier

NewNotifier new a notifiee

func (*Notifier) Loop

func (notifier *Notifier) Loop(parent goprocess.Process)

Loop handle notifiee message

func (*Notifier) Notify

func (notifier *Notifier) Notify(msg Message)

Notify message to notifier

func (*Notifier) Subscribe

func (notifier *Notifier) Subscribe(notifiee *Notifiee)

Subscribe notifier

func (*Notifier) UnSubscribe

func (notifier *Notifier) UnSubscribe(notifiee *Notifiee)

UnSubscribe notifiee

type ScoreManager

type ScoreManager struct {
	Mutex sync.Mutex
	// contains filtered or unexported fields
}

ScoreManager is an object to maitian all scores of peers

func NewScoreManager

func NewScoreManager(parent goprocess.Process, bus eventbus.Bus, boxPeer *BoxPeer) *ScoreManager

NewScoreManager returns new ScoreManager.

type Table

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

Table peer route table struct.

func NewTable

func NewTable(peer *BoxPeer) *Table

NewTable return a new route table.

func (*Table) AddPeerToTable

func (t *Table) AddPeerToTable(conn *Conn)

AddPeerToTable add peer route table.

func (*Table) AddPeers

func (t *Table) AddPeers(conn *Conn, peers *p2ppb.Peers)

AddPeers add peers to route table

func (*Table) GetRandomPeers

func (t *Table) GetRandomPeers(pid peer.ID) []peerstore.PeerInfo

GetRandomPeers get random peers

func (*Table) Loop

func (t *Table) Loop(parent goprocess.Process)

Loop for discover new peer.

Directories

Path Synopsis
mock
table command

Jump to

Keyboard shortcuts

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