p2p

package
v0.0.0-...-7c12c5a Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2015 License: GPL-2.0, GPL-3.0 Imports: 33 Imported by: 0

README

tendermint/p2p

tendermint/p2p provides an abstraction around peer-to-peer communication.

Peer/MConnection/Channel

Each peer has one MConnection (multiplex connection) instance.

multiplex noun a system or signal involving simultaneous transmission of several messages along a single channel of communication.

Each MConnection handles message transmission on multiple abstract communication Channels. Each channel has a globally unique byte id. The byte id and the relative priorities of each Channel are configured upon initialization of the connection.

There are two methods for sending messages:

func (m MConnection) Send(chID byte, msg interface{}) bool {}
func (m MConnection) TrySend(chID byte, msg interface{}) bool {}

Send(chID, msg) is a blocking call that waits until msg is successfully queued for the channel with the given id byte chID. The message msg is serialized using the tendermint/wire submodule's WriteBinary() reflection routine.

TrySend(chID, msg) is a nonblocking call that returns false if the channel's queue is full.

Send() and TrySend() are also exposed for each Peer.

Switch/Reactor

The Switch handles peer connections and exposes an API to receive incoming messages on Reactors. Each Reactor is responsible for handling incoming messages of one or more Channels. So while sending outgoing messages is typically performed on the peer, incoming messages are received on the reactor.

// Declare a MyReactor reactor that handles messages on MyChannelID.
type MyReactor struct{}

func (reactor MyReactor) GetChannels() []*ChannelDescriptor {
    return []*ChannelDescriptor{ChannelDescriptor{ID:MyChannelID, Priority: 1}}
}

func (reactor MyReactor) Receive(chID byte, peer *Peer, msgBytes []byte) {
    r, n, err := bytes.NewBuffer(msgBytes), new(int64), new(error)
    msgString := ReadString(r, n, err)
    fmt.Println(msgString)
}

// Other Reactor methods omitted for brevity
...

switch := NewSwitch([]Reactor{MyReactor{}})

...

// Send a random message to all outbound connections
for _, peer := range switch.Peers().List() {
    if peer.IsOutbound() {
        peer.Send(MyChannelID, "Here's a random message")
    }
}
PexReactor/AddrBook

A PEXReactor reactor implementation is provided to automate peer discovery.

book := p2p.NewAddrBook(config.App.GetString("AddrBookFile"))
pexReactor := p2p.NewPEXReactor(book)
...
switch := NewSwitch([]Reactor{pexReactor, myReactor, ...})

Documentation

Overview

Uses nacl's secret_box to encrypt a net.Conn. It is (meant to be) an implementation of the STS protocol. Note we do not (yet) assume that a remote peer's pubkey is known ahead of time, and thus we are technically still vulnerable to MITM. (TODO!) See docs/sts-final.pdf for more info

Index

Constants

View Source
const (
	PexChannel = byte(0x00)
)
View Source
const Version = "0.3.0"

Variables

View Source
var (
	ErrSwitchDuplicatePeer      = errors.New("Duplicate peer")
	ErrSwitchMaxPeersPerIPRange = errors.New("IP range has too many peers")
)

Functions

func NewNestedCounter

func NewNestedCounter() *nestedCounter

Types

type AddrBook

type AddrBook struct {
	QuitService
	// contains filtered or unexported fields
}

AddrBook - concurrency safe peer address manager

func NewAddrBook

func NewAddrBook(filePath string) *AddrBook

Use Start to begin processing asynchronous address updates.

func (*AddrBook) AddAddress

func (a *AddrBook) AddAddress(addr *NetAddress, src *NetAddress)

func (*AddrBook) AddOurAddress

func (a *AddrBook) AddOurAddress(addr *NetAddress)

func (*AddrBook) GetSelection

func (a *AddrBook) GetSelection() []*NetAddress

GetSelection randomly selects some addresses (old & new). Suitable for peer-exchange protocols.

func (*AddrBook) MarkAttempt

func (a *AddrBook) MarkAttempt(addr *NetAddress)

func (*AddrBook) MarkBad

func (a *AddrBook) MarkBad(addr *NetAddress)

func (*AddrBook) MarkGood

func (a *AddrBook) MarkGood(addr *NetAddress)

func (*AddrBook) NeedMoreAddrs

func (a *AddrBook) NeedMoreAddrs() bool

func (*AddrBook) OnStart

func (a *AddrBook) OnStart() error

func (*AddrBook) OnStop

func (a *AddrBook) OnStop()

func (*AddrBook) OurAddresses

func (a *AddrBook) OurAddresses() []*NetAddress

func (*AddrBook) PickAddress

func (a *AddrBook) PickAddress(newBias int) *NetAddress

Pick an address to connect to with new/old bias.

func (*AddrBook) Size

func (a *AddrBook) Size() int

type BaseReactor

type BaseReactor struct {
	QuitService // Provides Start, Stop, .Quit
	Switch      *Switch
}

func NewBaseReactor

func NewBaseReactor(log log15.Logger, name string, impl Reactor) *BaseReactor

func (*BaseReactor) AddPeer

func (_ *BaseReactor) AddPeer(peer *Peer)

func (*BaseReactor) GetChannels

func (_ *BaseReactor) GetChannels() []*ChannelDescriptor

func (*BaseReactor) Receive

func (_ *BaseReactor) Receive(chID byte, peer *Peer, msgBytes []byte)

func (*BaseReactor) RemovePeer

func (_ *BaseReactor) RemovePeer(peer *Peer, reason interface{})

func (*BaseReactor) SetSwitch

func (br *BaseReactor) SetSwitch(sw *Switch)

type Channel

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

TODO: lowercase. NOTE: not goroutine-safe.

type ChannelDescriptor

type ChannelDescriptor struct {
	ID                 byte
	Priority           int
	SendQueueCapacity  int
	RecvBufferCapacity int
}

func (*ChannelDescriptor) FillDefaults

func (chDesc *ChannelDescriptor) FillDefaults()

type DefaultListener

type DefaultListener struct {
	BaseService
	// contains filtered or unexported fields
}

Implements Listener

func (*DefaultListener) Connections

func (l *DefaultListener) Connections() <-chan net.Conn

A channel of inbound connections. It gets closed when the listener closes.

func (*DefaultListener) ExternalAddress

func (l *DefaultListener) ExternalAddress() *NetAddress

func (*DefaultListener) InternalAddress

func (l *DefaultListener) InternalAddress() *NetAddress

func (*DefaultListener) NetListener

func (l *DefaultListener) NetListener() net.Listener

NOTE: The returned listener is already Accept()'ing. So it's not suitable to pass into http.Serve().

func (*DefaultListener) OnStart

func (l *DefaultListener) OnStart() error

func (*DefaultListener) OnStop

func (l *DefaultListener) OnStop()

func (*DefaultListener) String

func (l *DefaultListener) String() string

type IPeerSet

type IPeerSet interface {
	Has(key string) bool
	Get(key string) *Peer
	List() []*Peer
	Size() int
}

IPeerSet has a (immutable) subset of the methods of PeerSet.

type Listener

type Listener interface {
	Connections() <-chan net.Conn
	InternalAddress() *NetAddress
	ExternalAddress() *NetAddress
	String() string
	Stop() bool
}

func NewDefaultListener

func NewDefaultListener(protocol string, lAddr string) Listener

type MConnection

type MConnection struct {
	BaseService

	LocalAddress  *NetAddress
	RemoteAddress *NetAddress
	// contains filtered or unexported fields
}

Each peer has one `MConnection` (multiplex connection) instance.

__multiplex__ *noun* a system or signal involving simultaneous transmission of several messages along a single channel of communication.

Each `MConnection` handles message transmission on multiple abstract communication `Channel`s. Each channel has a globally unique byte id. The byte id and the relative priorities of each `Channel` are configured upon initialization of the connection.

There are two methods for sending messages:

func (m MConnection) Send(chID byte, msg interface{}) bool {}
func (m MConnection) TrySend(chID byte, msg interface{}) bool {}

`Send(chID, msg)` is a blocking call that waits until `msg` is successfully queued for the channel with the given id byte `chID`, or until the request times out. The message `msg` is serialized using the `tendermint/wire` submodule's `WriteBinary()` reflection routine.

`TrySend(chID, msg)` is a nonblocking call that returns false if the channel's queue is full.

Inbound message bytes are handled with an onReceive callback function.

func NewMConnection

func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection

func (*MConnection) CanSend

func (c *MConnection) CanSend(chID byte) bool

func (*MConnection) OnStart

func (c *MConnection) OnStart() error

func (*MConnection) OnStop

func (c *MConnection) OnStop()

func (*MConnection) Send

func (c *MConnection) Send(chID byte, msg interface{}) bool

Queues a message to be sent to channel.

func (*MConnection) String

func (c *MConnection) String() string

func (*MConnection) TrySend

func (c *MConnection) TrySend(chID byte, msg interface{}) bool

Queues a message to be sent to channel. Nonblocking, returns true if successful.

type NetAddress

type NetAddress struct {
	IP   net.IP
	Port uint16
	// contains filtered or unexported fields
}

func NewNetAddress

func NewNetAddress(addr net.Addr) *NetAddress

TODO: socks proxies?

func NewNetAddressIPPort

func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress

func NewNetAddressString

func NewNetAddressString(addr string) *NetAddress

Also resolves the host if host is not an IP.

func (*NetAddress) Dial

func (na *NetAddress) Dial() (net.Conn, error)

func (*NetAddress) DialTimeout

func (na *NetAddress) DialTimeout(timeout time.Duration) (net.Conn, error)

func (*NetAddress) Equals

func (na *NetAddress) Equals(other interface{}) bool

func (*NetAddress) Less

func (na *NetAddress) Less(other interface{}) bool

func (*NetAddress) Local

func (na *NetAddress) Local() bool

func (*NetAddress) RFC1918

func (na *NetAddress) RFC1918() bool

func (*NetAddress) RFC3849

func (na *NetAddress) RFC3849() bool

func (*NetAddress) RFC3927

func (na *NetAddress) RFC3927() bool

func (*NetAddress) RFC3964

func (na *NetAddress) RFC3964() bool

func (*NetAddress) RFC4193

func (na *NetAddress) RFC4193() bool

func (*NetAddress) RFC4380

func (na *NetAddress) RFC4380() bool

func (*NetAddress) RFC4843

func (na *NetAddress) RFC4843() bool

func (*NetAddress) RFC4862

func (na *NetAddress) RFC4862() bool

func (*NetAddress) RFC6052

func (na *NetAddress) RFC6052() bool

func (*NetAddress) RFC6145

func (na *NetAddress) RFC6145() bool

func (*NetAddress) ReachabilityTo

func (na *NetAddress) ReachabilityTo(o *NetAddress) int

func (*NetAddress) Routable

func (na *NetAddress) Routable() bool

func (*NetAddress) String

func (na *NetAddress) String() string

func (*NetAddress) Valid

func (na *NetAddress) Valid() bool

For IPv4 these are either a 0 or all bits set address. For IPv6 a zero address or one that matches the RFC3849 documentation address format.

type PEXReactor

type PEXReactor struct {
	BaseReactor
	// contains filtered or unexported fields
}

PEXReactor handles PEX (peer exchange) and ensures that an adequate number of peers are connected to the switch.

func NewPEXReactor

func NewPEXReactor(book *AddrBook) *PEXReactor

func (*PEXReactor) AddPeer

func (pexR *PEXReactor) AddPeer(peer *Peer)

Implements Reactor

func (*PEXReactor) GetChannels

func (pexR *PEXReactor) GetChannels() []*ChannelDescriptor

Implements Reactor

func (*PEXReactor) OnStart

func (pexR *PEXReactor) OnStart() error

func (*PEXReactor) OnStop

func (pexR *PEXReactor) OnStop()

func (*PEXReactor) Receive

func (pexR *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte)

Implements Reactor Handles incoming PEX messages.

func (*PEXReactor) RemovePeer

func (pexR *PEXReactor) RemovePeer(peer *Peer, reason interface{})

Implements Reactor

func (*PEXReactor) RequestPEX

func (pexR *PEXReactor) RequestPEX(peer *Peer)

Asks peer for more addresses.

func (*PEXReactor) SendAddrs

func (pexR *PEXReactor) SendAddrs(peer *Peer, addrs []*NetAddress)

func (*PEXReactor) SetFireable

func (pexR *PEXReactor) SetFireable(evsw events.Fireable)

implements events.Eventable

type Peer

type Peer struct {
	BaseService

	*types.NodeInfo
	Key  string
	Data *CMap // User data.
	// contains filtered or unexported fields
}

func (*Peer) CanSend

func (p *Peer) CanSend(chID byte) bool

func (*Peer) Connection

func (p *Peer) Connection() *MConnection

func (*Peer) Equals

func (p *Peer) Equals(other *Peer) bool

func (*Peer) Get

func (p *Peer) Get(key string) interface{}

func (*Peer) IsOutbound

func (p *Peer) IsOutbound() bool

func (*Peer) OnStart

func (p *Peer) OnStart() error

func (*Peer) OnStop

func (p *Peer) OnStop()

func (*Peer) Send

func (p *Peer) Send(chID byte, msg interface{}) bool

func (*Peer) String

func (p *Peer) String() string

func (*Peer) TrySend

func (p *Peer) TrySend(chID byte, msg interface{}) bool

func (*Peer) WriteTo

func (p *Peer) WriteTo(w io.Writer) (n int64, err error)

type PeerSet

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

PeerSet is a special structure for keeping a table of peers. Iteration over the peers is super fast and thread-safe. We also track how many peers per IP range and avoid too many

func NewPeerSet

func NewPeerSet() *PeerSet

func (*PeerSet) Add

func (ps *PeerSet) Add(peer *Peer) error

Returns false if peer with key (PubKeyEd25519) is already in set or if we have too many peers from the peer's IP range

func (*PeerSet) Get

func (ps *PeerSet) Get(peerKey string) *Peer

func (*PeerSet) Has

func (ps *PeerSet) Has(peerKey string) bool

func (*PeerSet) HasMaxForIPRange

func (ps *PeerSet) HasMaxForIPRange(conn net.Conn) (ok bool)

Check if we have too many IPs in the IP range of the incoming connection Thread safe

func (*PeerSet) List

func (ps *PeerSet) List() []*Peer

threadsafe list of peers.

func (*PeerSet) Remove

func (ps *PeerSet) Remove(peer *Peer)

func (*PeerSet) Size

func (ps *PeerSet) Size() int

type PexMessage

type PexMessage interface{}

func DecodeMessage

func DecodeMessage(bz []byte) (msgType byte, msg PexMessage, err error)

type Reactor

type Reactor interface {
	Service // Start, Stop

	SetSwitch(*Switch)
	GetChannels() []*ChannelDescriptor
	AddPeer(peer *Peer)
	RemovePeer(peer *Peer, reason interface{})
	Receive(chID byte, peer *Peer, msgBytes []byte)
}

type SecretConnection

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

Implements net.Conn

func MakeSecretConnection

func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey acm.PrivKeyEd25519) (*SecretConnection, error)

Performs handshake and returns a new authenticated SecretConnection. Returns nil if error in handshake. Caller should call conn.Close() See docs/sts-final.pdf for more information.

func (*SecretConnection) Close

func (sc *SecretConnection) Close() error

Implements net.Conn

func (*SecretConnection) LocalAddr

func (sc *SecretConnection) LocalAddr() net.Addr

func (*SecretConnection) Read

func (sc *SecretConnection) Read(data []byte) (n int, err error)

CONTRACT: data smaller than dataMaxSize is read atomically.

func (*SecretConnection) RemoteAddr

func (sc *SecretConnection) RemoteAddr() net.Addr

func (*SecretConnection) RemotePubKey

func (sc *SecretConnection) RemotePubKey() acm.PubKeyEd25519

Returns authenticated remote pubkey

func (*SecretConnection) SetDeadline

func (sc *SecretConnection) SetDeadline(t time.Time) error

func (*SecretConnection) SetReadDeadline

func (sc *SecretConnection) SetReadDeadline(t time.Time) error

func (*SecretConnection) SetWriteDeadline

func (sc *SecretConnection) SetWriteDeadline(t time.Time) error

func (*SecretConnection) Write

func (sc *SecretConnection) Write(data []byte) (n int, err error)

Writes encrypted frames of `sealedFrameSize` CONTRACT: data smaller than dataMaxSize is read atomically.

type Switch

type Switch struct {
	BaseService
	// contains filtered or unexported fields
}

The `Switch` handles peer connections and exposes an API to receive incoming messages on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one or more `Channels`. So while sending outgoing messages is typically performed on the peer, incoming messages are received on the reactor.

func NewSwitch

func NewSwitch() *Switch

func (*Switch) AddListener

func (sw *Switch) AddListener(l Listener)

Not goroutine safe.

func (*Switch) AddPeerWithConnection

func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, error)

NOTE: This performs a blocking handshake before the peer is added. CONTRACT: Iff error is returned, peer is nil, and conn is immediately closed.

func (*Switch) AddReactor

func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor

Not goroutine safe.

func (*Switch) Broadcast

func (sw *Switch) Broadcast(chID byte, msg interface{}) chan bool

Broadcast runs a go routine for each attempted send, which will block trying to send for defaultSendTimeoutSeconds. Returns a channel which receives success values for each attempted send (false if times out)

func (*Switch) DialPeerWithAddress

func (sw *Switch) DialPeerWithAddress(addr *NetAddress) (*Peer, error)

func (*Switch) IsDialing

func (sw *Switch) IsDialing(addr *NetAddress) bool

func (*Switch) IsListening

func (sw *Switch) IsListening() bool

Not goroutine safe.

func (*Switch) Listeners

func (sw *Switch) Listeners() []Listener

Not goroutine safe.

func (*Switch) NodeInfo

func (sw *Switch) NodeInfo() *types.NodeInfo

Not goroutine safe.

func (*Switch) NumPeers

func (sw *Switch) NumPeers() (outbound, inbound, dialing int)

Returns the count of outbound/inbound and outbound-dialing peers.

func (*Switch) OnStart

func (sw *Switch) OnStart() error

Switch.Start() starts all the reactors, peers, and listeners.

func (*Switch) OnStop

func (sw *Switch) OnStop()

func (*Switch) Peers

func (sw *Switch) Peers() IPeerSet

func (*Switch) Reactor

func (sw *Switch) Reactor(name string) Reactor

Not goroutine safe.

func (*Switch) Reactors

func (sw *Switch) Reactors() map[string]Reactor

Not goroutine safe.

func (*Switch) SetNodeInfo

func (sw *Switch) SetNodeInfo(nodeInfo *types.NodeInfo)

Not goroutine safe.

func (*Switch) SetNodePrivKey

func (sw *Switch) SetNodePrivKey(nodePrivKey acm.PrivKeyEd25519)

Not goroutine safe. NOTE: Overwrites sw.nodeInfo.PubKey

func (*Switch) StopPeerForError

func (sw *Switch) StopPeerForError(peer *Peer, reason interface{})

Disconnect from a peer due to external error. TODO: make record depending on reason.

func (*Switch) StopPeerGracefully

func (sw *Switch) StopPeerGracefully(peer *Peer)

Disconnect from a peer gracefully. TODO: handle graceful disconnects.

type SwitchEventDonePeer

type SwitchEventDonePeer struct {
	Peer  *Peer
	Error interface{}
}

type SwitchEventNewPeer

type SwitchEventNewPeer struct {
	Peer *Peer
}

type TypedMessage

type TypedMessage struct {
	Type byte
	Msg  interface{}
}

Convenience struct for writing typed messages. Reading requires a custom decoder that switches on the first type byte of a byteslice.

func (TypedMessage) String

func (tm TypedMessage) String() string

Directories

Path Synopsis
Taken from taipei-torrent Just enough UPnP to be able to forward ports
Taken from taipei-torrent Just enough UPnP to be able to forward ports

Jump to

Keyboard shortcuts

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