p2p

package
v2.1.3+incompatible Latest Latest
Warning

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

Go to latest
Published: May 22, 2019 License: GPL-3.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultNodeName        = "vite-node"
	DefaultMaxPeers        = 60
	DefaultMaxInboundRatio = 2
	DefaultOutboundPeers   = 5
	DefaultSuperiorPeers   = 70
	DefaultMinPeers        = DefaultOutboundPeers
	DefaultMaxPendingPeers = 10
	DefaultFilePort        = 8484
	DirName                = "net"
	DBDirName              = "db"
)

Variables

This section is empty.

Functions

func Disconnect

func Disconnect(c MsgWriteCloser, err error) (e2 error)

func PutVarint

func PutVarint(buf []byte, n uint) (m byte)

func Varint

func Varint(buf []byte) (n uint)

Types

type Authenticator

type Authenticator interface {
	// Authenticate the connection, connection will be disconnected if return false
	Authenticate() bool
}

Authenticator will authenticate all inbound connection whether can access our server

type Code

type Code = byte
const (
	CodeDisconnect  Code = 1
	CodeHandshake   Code = 2
	CodeControlFlow Code = 3
	CodeHeartBeat   Code = 4

	CodeGetHashList       Code = 25
	CodeHashList          Code = 26
	CodeGetSnapshotBlocks Code = 27
	CodeSnapshotBlocks    Code = 28
	CodeGetAccountBlocks  Code = 29
	CodeAccountBlocks     Code = 30
	CodeNewSnapshotBlock  Code = 31
	CodeNewAccountBlock   Code = 32

	CodeSyncHandshake   Code = 60
	CodeSyncHandshakeOK Code = 61
	CodeSyncRequest     Code = 62
	CodeSyncReady       Code = 63

	CodeException Code = 127
	CodeTrace     Code = 128
)

type Codec

type Codec interface {
	MsgReadWriter
	Close() error
	SetReadTimeout(timeout time.Duration)
	SetWriteTimeout(timeout time.Duration)
	SetTimeout(timeout time.Duration)
	Address() net.Addr
}

Codec is an transport can encode messages to bytes, transmit bytes, then decode bytes to messages

func MockPipe

func MockPipe() (c1, c2 Codec)

func NewTransport

func NewTransport(conn net.Conn, minCompressLength int, readTimeout, writeTimeout time.Duration) Codec

type CodecFactory

type CodecFactory interface {
	CreateCodec(conn net.Conn) Codec
}

type Config

type Config struct {
	*discovery.Config

	// Discover means whether discover other nodes in the networks, default true
	Discover bool

	// Name is our node name, NO need to be unique in the whole network, just for readability, default is `vite-node`
	Name string

	MaxPeers int

	MaxInboundRatio int

	// MinPeers server will keep finding nodes and try to connect until number of peers is larger than `MinPeers`,
	// default 5
	MinPeers int

	// MaxPendingPeers how many inbound peers can be connect concurrently, more inbound connection will be blocked
	// this value is for defend DDOS attack, default 10
	MaxPendingPeers int

	// StaticNodes will be connect directly
	StaticNodes []string

	FilePublicAddress string
	FilePort          int

	MineKey ed25519.PrivateKey // will be set in net
	// contains filtered or unexported fields
}

Config is the essential configuration to create a p2p server

func (*Config) Ensure

func (cfg *Config) Ensure() (err error)

type Exception

type Exception byte
const (
	ExpMissing     Exception = iota // I don`t have the resource you requested
	ExpUnsolicited                  // the request must have pre-checked
	ExpUnauthorized
	ExpServerError
	ExpChunkNotMatch
	ExpOther
)

func (*Exception) Deserialize

func (exp *Exception) Deserialize(buf []byte) error

func (Exception) Error

func (exp Exception) Error() string

func (Exception) Serialize

func (exp Exception) Serialize() ([]byte, error)

func (Exception) String

func (exp Exception) String() string

type HandshakeMsg

type HandshakeMsg struct {
	Version int64

	NetID int64

	Name string

	ID vnode.NodeID

	Timestamp int64

	Height  uint64
	Head    types.Hash
	Genesis types.Hash

	Key   ed25519.PublicKey // is producer
	Token []byte

	FileAddress []byte
}

func (*HandshakeMsg) Deserialize

func (b *HandshakeMsg) Deserialize(data []byte) (err error)

func (*HandshakeMsg) Serialize

func (b *HandshakeMsg) Serialize() (data []byte, err error)

type Handshaker

type Handshaker interface {
	ReceiveHandshake(c Codec) (peer PeerMux, err error)
	InitiateHandshake(c Codec, id vnode.NodeID) (peer PeerMux, err error)
}

type Level

type Level = byte
const (
	Inbound  Level = 0
	Outbound Level = 1
	Trusted  Level = 2
	Superior Level = 3
)

type MockCodec

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

func (*MockCodec) Address

func (m *MockCodec) Address() net.Addr

func (*MockCodec) Close

func (m *MockCodec) Close() error

func (*MockCodec) ReadMsg

func (m *MockCodec) ReadMsg() (msg Msg, err error)

func (*MockCodec) SetReadTimeout

func (m *MockCodec) SetReadTimeout(timeout time.Duration)

func (*MockCodec) SetTimeout

func (m *MockCodec) SetTimeout(timeout time.Duration)

func (*MockCodec) SetWriteTimeout

func (m *MockCodec) SetWriteTimeout(timeout time.Duration)

func (*MockCodec) WriteMsg

func (m *MockCodec) WriteMsg(msg Msg) (err error)

type Msg

type Msg struct {
	Code       Code
	Id         uint32
	Payload    []byte
	ReceivedAt time.Time
	Sender     Peer
}

func (Msg) Recycle

func (m Msg) Recycle()

Recycle will put Msg.Payload back to pool

type MsgHandler

type MsgHandler = func(msg Msg) error

type MsgId

type MsgId = uint32

type MsgReadWriter

type MsgReadWriter interface {
	MsgReader
	MsgWriter
}

type MsgReader

type MsgReader interface {
	ReadMsg() (Msg, error)
}

type MsgWriteCloser

type MsgWriteCloser interface {
	MsgWriter
	io.Closer
}

type MsgWriter

type MsgWriter interface {
	WriteMsg(Msg) error
}

type NodeInfo

type NodeInfo struct {
	// ID is the hex-encoded NodeID
	ID        string     `json:"id"`
	Name      string     `json:"name"`
	NetID     int        `json:"netId"`
	Version   int        `json:"version"`
	Address   string     `json:"address"`
	PeerCount int        `json:"peerCount"`
	Peers     []PeerInfo `json:"peers"`
}

NodeInfo represent current p2p node

type P2P

type P2P interface {
	Config() Config
	Start() error
	Stop() error
	Connect(node string) error
	ConnectNode(node *vnode.Node) error
	Info() NodeInfo
	Register(pt Protocol) error
	Discovery() discovery.Discovery
	Node() *vnode.Node
}

func New

func New(cfg *Config) P2P

type Peer

type Peer interface {
	// contains filtered or unexported methods
}

type PeerError

type PeerError byte
const (
	PeerNetworkError PeerError = iota // read/write timeout, read/write error
	PeerDifferentNetwork
	PeerTooManyPeers
	PeerTooManySameNetPeers
	PeerTooManyInboundPeers
	PeerAlreadyConnected
	PeerIncompatibleVersion
	PeerQuitting
	PeerNotHandshakeMsg
	PeerInvalidSignature
	PeerConnectSelf
	PeerUnknownMessage
	PeerUnmarshalError
	PeerNoPermission
	PeerBanned
	PeerDifferentGenesis
	PeerInvalidBlock
	PeerInvalidMessage
	PeerResponseTimeout
	PeerInvalidToken
	PeerUnknownReason PeerError = 255
)

func (PeerError) Error

func (e PeerError) Error() string

func (PeerError) Serialize

func (e PeerError) Serialize() ([]byte, error)

func (PeerError) String

func (e PeerError) String() string

type PeerInfo

type PeerInfo struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	Version    int    `json:"version"`
	Height     uint64 `json:"height"`
	Address    string `json:"address"`
	Level      Level  `json:"level"`
	CreateAt   string `json:"createAt"`
	ReadQueue  int    `json:"readQueue"`
	WriteQueue int    `json:"writeQueue"`
}

type PeerMux

type PeerMux interface {
	// contains filtered or unexported methods
}

func NewPeer

func NewPeer(id vnode.NodeID, name string, height uint64, head types.Hash, fileAddress string, version int, c Codec, level Level, proto Protocol) PeerMux

type Protocol

type Protocol interface {
	// ProtoData return the data to handshake, will transmit to peer with HandshakeMsg.
	ProtoData() (height uint64, head types.Hash, genesis types.Hash)

	// ReceiveHandshake handle the HandshakeMsg and protoData from peer.
	// The connection will be disconnected if err is not nil.
	// Level MUST small than 255, each level has it`s strategy, Eg, access by count-constraint, broadcast priority
	// If peer support multiple protocol, the highest protocol level will be the peer`s level.
	// As default, there are 4 levels from low to high: Inbound - Outbound - Trusted - Superior
	ReceiveHandshake(msg *HandshakeMsg) (level Level, err error)

	// Handle message from sender, if the return error is not nil, will disconnect with peer
	Handle(msg Msg) error

	// State get the Protocol state, will be sent to peers by heartbeat
	State() []byte

	// OnPeerAdded will be invoked after Peer run
	// peer will be closed if return error is not nil
	OnPeerAdded(peer Peer) error

	// OnPeerRemoved will be invoked after Peer closed
	OnPeerRemoved(peer Peer) error
}

Protocol is a abstract communication layer above connection, there can be multi protocol on a connection. A Protocol usually has many different message codes, each code has a handler to handle the message from peer.

type Serializable

type Serializable interface {
	Serialize() ([]byte, error)
}

type Server

type Server interface {
	Start() error
	Stop() error
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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