Documentation
¶
Index ¶
- Constants
- Variables
- func Data2Hash(data []byte) (hash []byte)
- func FindInterfaceByIP(ip net.IP) (iface *net.Interface, ipnet *net.IPNet)
- func IsIPLocal(ip net.IP) bool
- func IsIPv4(IP net.IP) bool
- func IsIPv6(IP net.IP) bool
- func IsNetworkErrorFatal(err error) bool
- func LoadConfig(Filename string, ConfigOut interface{}) (status int, err error)
- func NetworkListIPs() (IPs []net.IP, err error)
- func NewIPList() (list *ipList)
- func NewPrivateKey() (publicKey ed25519.PublicKey, privateKey ed25519.PrivateKey, err error)
- func PublicKeyFromPeerID(peerID string) (publicKey ed25519.PublicKey, err error)
- func SaveConfig(Filename string, Config interface{}) (err error)
- func SaveConfigs(Filename string, Configs ...interface{}) (err error)
- type Backend
- func (backend *Backend) AsyncSearch(Action int, Key []byte, Timeout, TimeoutIR time.Duration, Alpha int) (client *dht.SearchClient)
- func (backend *Backend) Connect()
- func (backend *Backend) DeleteAccount()
- func (backend *Backend) ExportPrivateKey() (privateKey ed25519.PrivateKey, publicKey ed25519.PublicKey)
- func (backend *Backend) FeatureSupport() (feature byte)
- func (backend *Backend) FindBlockchain(publicKey ed25519.PublicKey) (search *dht.SearchClient, err error)
- func (backend *Backend) FindNode(publicKey ed25519.PublicKey, Timeout time.Duration) (node *dht.Node, peer *PeerInfo, err error)
- func (backend *Backend) GetNetworks(networkType int) (networksConnected []*Network)
- func (backend *Backend) IsAmongClosest(publicKey ed25519.PublicKey, count int) bool
- func (backend *Backend) IsNodeContact(publicKey ed25519.PublicKey) (node *dht.Node, peer *PeerInfo)
- func (backend *Backend) LiteSessions() (sessions []*protocol.LiteSession)
- func (backend *Backend) LogError(function, format string, v ...interface{})
- func (backend *Backend) PeerlistAdd(PublicKey ed25519.PublicKey, connections ...*Connection) (peer *PeerInfo, added bool)
- func (backend *Backend) PeerlistCount() (count int)
- func (backend *Backend) PeerlistGet() (peers []*PeerInfo)
- func (backend *Backend) PeerlistLookup(publicKey ed25519.PublicKey) (peer *PeerInfo)
- func (backend *Backend) PeerlistRemove(peer *PeerInfo)
- func (backend *Backend) ReadBlock(PublicKey ed25519.PublicKey, Version, BlockNumber uint64) (decoded *blockchain.BlockDecoded, raw []byte, found bool, err error)
- func (backend *Backend) ReadFile(PublicKey ed25519.PublicKey, Version, BlockNumber uint64, FileID uuid.UUID) (file blockchain.BlockRecordFile, raw []byte, found bool, err error)
- func (backend *Backend) SaveConfig()
- func (backend *Backend) SelfPublicKey() ed25519.PublicKey
- func (backend *Backend) SelfUserAgent() string
- func (backend *Backend) SendChatAll(text string)
- type BlockTransferStats
- type BlockchainCache
- func (cache *BlockchainCache) Drop(publicKey ed25519.PublicKey, reason uint8) (err error)
- func (cache *BlockchainCache) Keep(publicKey ed25519.PublicKey, reason uint8, until time.Time) (err error)
- func (cache *BlockchainCache) Reason(publicKey ed25519.PublicKey, reason uint8) (since, until time.Time, found bool)
- func (cache *BlockchainCache) SeenBlockchainVersion(peer *PeerInfo)
- type BlockchainStoring
- type Config
- type Connection
- type FileTransferStats
- type Filters
- type Network
- func (network *Network) AutoAssignPort(ip net.IP, port int) (err error)
- func (network *Network) BroadcastIPv4() (err error)
- func (network *Network) BroadcastIPv4Listen()
- func (network *Network) BroadcastIPv4Send() (err error)
- func (network *Network) GetAdapterName() string
- func (network *Network) GetListen() (listen *net.UDPAddr, multicastIPv6 net.IP, broadcastIPv4 []net.IP, ...)
- func (network *Network) Listen()
- func (network *Network) MulticastIPv6Join() (err error)
- func (network *Network) MulticastIPv6Listen()
- func (network *Network) MulticastIPv6Send() (err error)
- func (network *Network) SelfReportedPorts() (portI, portE uint16)
- func (network *Network) Terminate()
- type Networks
- type PeerInfo
- func (peer *PeerInfo) BlockDownload(BlockchainPublicKey ed25519.PublicKey, BlockchainVersion uint64, ...) (height uint64, err error)
- func (peer *PeerInfo) BlockTransferRequest(BlockchainPublicKey ed25519.PublicKey, BlockchainVersion uint64, ...) (udtConn *udt.UDTSocket, virtualConn *VirtualPacketConn, err error)
- func (peer *PeerInfo) Chat(text string)
- func (peer *PeerInfo) FileTransferRequestUDT(hash []byte, offset, limit uint64) (udtConn *udt.UDTSocket, virtualConn *VirtualPacketConn, err error)
- func (peer *PeerInfo) GetConnection2Share(allowLocal, allowIPv4, allowIPv6 bool) (connection *Connection)
- func (peer *PeerInfo) GetConnections(active bool) (connections []*Connection)
- func (peer *PeerInfo) GetConnections2Share(allowLocal, allowIPv4, allowIPv6 bool, limit int) (connections []*Connection)
- func (peer *PeerInfo) GetRTT() (rtt time.Duration)
- func (peer *PeerInfo) IsActive() bool
- func (peer *PeerInfo) IsBehindNAT() (result bool)
- func (peer *PeerInfo) IsConnectable(allowLocal, allowIPv4, allowIPv6 bool) bool
- func (peer *PeerInfo) IsConnectionActive() bool
- func (peer *PeerInfo) IsPortForward() (result bool)
- func (peer *PeerInfo) IsVirtual() bool
- func (peer *PeerInfo) Ping()
- type VirtualPacketConn
Constants ¶
const ( ConnectionActive = iota ConnectionInactive ConnectionRemoved ConnectionRedundant // Same as active. Incoming packets are accepted. Outgoing use only for redundancy. Reduces ping overhead. )
Connection status
const ( ExitSuccess = 0 // This is actually never used. ExitErrorConfigAccess = 1 // Error accessing the config file. ExitErrorConfigRead = 2 // Error reading the config file. ExitErrorConfigParse = 3 // Error parsing the config file. ExitErrorLogInit = 4 // Error initializing log file. ExitParamWebapiInvalid = 5 // Parameter for webapi is invalid. ExitPrivateKeyCorrupt = 6 // Private key is corrupt. ExitPrivateKeyCreate = 7 // Cannot create a new private key. ExitBlockchainCorrupt = 8 // Blockchain is corrupt. ExitGraceful = 9 // Graceful shutdown. ExitParamApiKeyInvalid = 10 // API key parameter is invalid. ExitErrorLocked = 11 // The lock file of the config file is locked by another process. ExitErrorLockFile = 12 // Error opening or locking the lock file of the config file. STATUS_CONTROL_C_EXIT = 0xC000013A // The application terminated as a result of a CTRL+C. This is a Windows NTSTATUS value. )
Exit codes signal why the application exited. These are universal between clients developed by the Peernet organization. Clients are encouraged to log additional details in a log file. 3rd party clients may define additional exit codes.
const ( TypeBinary = iota // Binary/unspecified TypeText // Plain text TypePicture // Picture of any format TypeVideo // Video TypeAudio // Audio TypeDocument // Any document file, including office documents, PDFs, power point, spreadsheets TypeExecutable // Any executable file, OS independent TypeContainer // Container files like ZIP, RAR, TAR, ISO TypeCompressed // Compressed files like GZ, BZ TypeFolder // Virtual folder TypeEbook // Ebook )
General content types of data.
const ( FormatBinary = iota // Binary/unspecified FormatPDF // PDF document FormatWord // Word document FormatExcel // Excel FormatPowerpoint // Powerpoint FormatPicture // Pictures (including GIF, excluding icons) FormatAudio // Audio files FormatVideo // Video files FormatContainer // Compressed files including ZIP, RAR, TAR and others FormatHTML // HTML file FormatText // Text file FormatEbook // Ebook file FormatCompressed // Compressed file FormatDatabase // Database file FormatEmail // Single email FormatCSV // CSV file FormatFolder // Virtual folder FormatExecutable // Executable file FormatInstaller // Installer FormatAPK // APK FormatISO // ISO )
File formats. New ones may be added to the list as required.
const ( DirectionIn = 0 DirectionOut = 1 DirectionBi = 2 )
Transfer directions
const ReplyTimeout = 20
ReplyTimeout is the round-trip timeout for message sequences.
const Version = "Alpha 11/2026-11-30"
Version is the current core library version
Variables ¶
var ConfigDefault []byte
Functions ¶
func FindInterfaceByIP ¶
FindInterfaceByIP finds an interface based on the IP. The IP must be available at the interface.
func IsIPLocal ¶
IsIPLocal reports whether ip is a private (local) address. The identification of private, or local, unicast addresses uses address type indentification as defined in RFC 1918 for ip4 and RFC 4193 (fc00::/7) for ip6 with the exception of ip4 directed broadcast addresses. Unassigned, reserved, multicast and limited-broadcast addresses are not handled and will return false. Link-local addresses are included in this check: 169.254.0.0/16 (RFC 3927) for ip4 and fe80::/10 for ip6. Loopback addresses are included in this check: 127.0.0.0/8 for ip4 and ::1 for ip6.
func IsNetworkErrorFatal ¶
IsNetworkErrorFatal checks if a network error indicates a broken connection. Not every network error indicates a broken connection. This function prevents from over-dropping connections.
func LoadConfig ¶
LoadConfig reads the YAML configuration file and unmarshals it into the provided structure. If the config file does not exist or is empty, it will fall back to the default config which is hardcoded. Status is of type ExitX.
func NetworkListIPs ¶
NetworkListIPs returns a list of all IPs
func NewPrivateKey ¶
func NewPrivateKey() (publicKey ed25519.PublicKey, privateKey ed25519.PrivateKey, err error)
NewPrivateKey creates a new Ed25519 public-private key pair
func PublicKeyFromPeerID ¶
PublicKeyFromPeerID decodes the peer ID (hex encoded) into a public key.
func SaveConfig ¶
SaveConfig stores the config.
func SaveConfigs ¶
SaveConfigs stores the multiple configurations into a single file. They are essentially merged. It is the callers responsibility to make sure no field collision ensue.
Types ¶
type Backend ¶
type Backend struct {
ConfigFilename string // Filename of the configuration file.
Config *Config // Core configuration
ConfigClient interface{} // Custom configuration from the client
Filters Filters // Filters allow to install hooks.
GlobalBlockchainCache *BlockchainCache // Caches blockchains of other peers.
SearchIndex *search.SearchIndexStore // Search index of blockchain records.
UserBlockchain *blockchain.Blockchain // UserBlockchain is the user's blockchain and exports functions to directly read and write it
UserWarehouse *warehouse.Warehouse // UserWarehouse is the user's warehouse for storing files that are shared
// Stdout bundles any output for the end-user. Writers may subscribe/unsubscribe.
Stdout *multiWriter
// contains filtered or unexported fields
}
The Backend represents an instance of a Peernet client to be used by a frontend. Global variables and init functions are to be merged.
func Init ¶
func Init(UserAgent string, ConfigFilename string, Filters *Filters, ConfigOut interface{}) (backend *Backend, status int, err error)
Init initializes the client. If the config file does not exist or is empty, a default one will be created. The User Agent must be provided in the form "Application Name/1.0". The file "[ConfigFilename].lock" is locked until the process ends. Only one process at a time can be initialized with a config file. The returned status is of type ExitX. Anything other than ExitSuccess indicates a fatal failure.
func (*Backend) AsyncSearch ¶
func (backend *Backend) AsyncSearch(Action int, Key []byte, Timeout, TimeoutIR time.Duration, Alpha int) (client *dht.SearchClient)
AsyncSearch creates an async search for the given key in the DHT. Timeout is the total time the search may take, covering all information requests. TimeoutIR is the time an information request may take. Alpha is the number of concurrent requests that will be performed.
func (*Backend) Connect ¶
func (backend *Backend) Connect()
Connect starts bootstrapping and local peer discovery.
func (*Backend) DeleteAccount ¶
func (backend *Backend) DeleteAccount()
DeleteAccount deletes the account
func (*Backend) ExportPrivateKey ¶
func (backend *Backend) ExportPrivateKey() (privateKey ed25519.PrivateKey, publicKey ed25519.PublicKey)
ExportPrivateKey returns the peers public and private key
func (*Backend) FeatureSupport ¶
FeatureSupport returns supported features by this peer
func (*Backend) FindBlockchain ¶
func (backend *Backend) FindBlockchain(publicKey ed25519.PublicKey) (search *dht.SearchClient, err error)
FindBlockchain starts a lookup in DHT B for the peers that store the blockchain of the Peer ID. Non-blocking. Each storing peer that a peer reports is handed over on the Storing channel of the search, the Info of its StoringNode is a *BlockchainStoring. A peer may be reported by several peers. The caller reads the channel until TerminateSignal of the search is closed. The lookup ends when the gamma closest peers known have all answered, or when no peer is left to ask; the caller may end it earlier by terminating the search.
func (*Backend) FindNode ¶
func (backend *Backend) FindNode(publicKey ed25519.PublicKey, Timeout time.Duration) (node *dht.Node, peer *PeerInfo, err error)
FindNode finds a peer via the DHT. A peer that is found answered the lookup. If it answered via a relay only, it is not in the peer list and the returned peer is a virtual one that is reached via that relay.
func (*Backend) GetNetworks ¶
GetNetworks returns the list of connected networks
func (*Backend) IsAmongClosest ¶
IsAmongClosest returns whether the own Peer ID is among the count Peer IDs closest to the public key, out of the own Peer ID and the peers in the routing table. The peer with the public key itself is left out.
func (*Backend) IsNodeContact ¶
IsNodeContact checks if the peer is a contact in the local DHT routing table
func (*Backend) LiteSessions ¶
func (backend *Backend) LiteSessions() (sessions []*protocol.LiteSession)
List of all lite sessions
func (*Backend) PeerlistAdd ¶
func (backend *Backend) PeerlistAdd(PublicKey ed25519.PublicKey, connections ...*Connection) (peer *PeerInfo, added bool)
PeerlistAdd adds a new peer to the peer list. It does not validate the peer info. If the peer is already added, it does nothing. Connections must be live.
func (*Backend) PeerlistCount ¶
PeerlistCount returns the current count of peers in the peer list
func (*Backend) PeerlistGet ¶
PeerlistGet returns the full peer list
func (*Backend) PeerlistLookup ¶
PeerlistLookup returns the peer from the list with the public key
func (*Backend) PeerlistRemove ¶
PeerlistRemove removes a peer from the peer list.
func (*Backend) ReadBlock ¶
func (backend *Backend) ReadBlock(PublicKey ed25519.PublicKey, Version, BlockNumber uint64) (decoded *blockchain.BlockDecoded, raw []byte, found bool, err error)
ReadBlock reads a block and decodes the records. This may be a block of the user's blockchain, or any other that is cached in the global blockchain cache.
func (*Backend) ReadFile ¶
func (backend *Backend) ReadFile(PublicKey ed25519.PublicKey, Version, BlockNumber uint64, FileID uuid.UUID) (file blockchain.BlockRecordFile, raw []byte, found bool, err error)
ReadFile decodes a file from the given blockchain (the user or any other cached). The block number must be provided.
func (*Backend) SaveConfig ¶
func (backend *Backend) SaveConfig()
SaveConfig stores the current runtime config to file. Any foreign settings not present in the Config structure will be deleted.
func (*Backend) SelfPublicKey ¶
SelfPublicKey returns the public key (= peer ID) of this peer. It is also the peer's key in the DHT.
func (*Backend) SelfUserAgent ¶
SelfUserAgent returns the User Agent
func (*Backend) SendChatAll ¶
SendChatAll sends a text message to all peers
type BlockTransferStats ¶
type BlockchainCache ¶
type BlockchainCache struct {
BlockchainDirectory string // The directory for storing blockchains in a key-value store.
MaxBlockchainSize uint64 // Max size of one cached blockchain in bytes.
MaxSize uint64 // Max size of all cached blockchains in bytes. 0 = unlimited.
Store *blockchain.MultiStore
// contains filtered or unexported fields
}
The blockchain cache stores blockchains. A copy of a blockchain is kept while a reason is set for it. The client sets the reasons, see Keep. A copy that no reason is left for is deleted.
func (*BlockchainCache) Drop ¶
func (cache *BlockchainCache) Drop(publicKey ed25519.PublicKey, reason uint8) (err error)
Drop ends a reason for which the blockchain is kept in the cache.
func (*BlockchainCache) Keep ¶
func (cache *BlockchainCache) Keep(publicKey ed25519.PublicKey, reason uint8, until time.Time) (err error)
Keep sets a reason for which the blockchain is kept in the cache, until the given time. A reason is a number; its meaning is the client's. Setting a reason that has not ended changes the time it ends and leaves the time it was set. If the blockchain was kept for no reason before and its owner is in the peer list, the copy is updated at once.
func (*BlockchainCache) Reason ¶
func (cache *BlockchainCache) Reason(publicKey ed25519.PublicKey, reason uint8) (since, until time.Time, found bool)
Reason returns the time a reason for which the blockchain is kept in the cache was set, and the time it ends. A reason is found until it ends.
func (*BlockchainCache) SeenBlockchainVersion ¶
func (cache *BlockchainCache) SeenBlockchainVersion(peer *PeerInfo)
SeenBlockchainVersion shall be called with information about another peer's blockchain. It updates the copy if a reason is set to keep the blockchain. It requests the blocks that the cache does not hold yet, up to the height the peer reports, while the copy and the cache have room for them. If the reported version number is newer, all existing blocks are immediately deleted.
type BlockchainStoring ¶
type BlockchainStoring struct {
Peer *PeerInfo // The peer that stores the blockchain. A peer that is not in the peer list is a virtual one.
Version uint64 // Blockchain version stored
Height uint64 // Blockchain height stored: the count of blocks stored from block 0 on, without a gap
Time time.Time // Time of its blockchain record
}
BlockchainStoring is a peer that stores a blockchain, as a lookup in DHT B reports it. Its blockchain record is valid.
type Config ¶
type Config struct {
// Locations of important files and folders
LogFile string `yaml:"LogFile"` // Log file. It contains informational and error messages.
BlockchainMain string `yaml:"BlockchainMain"` // Blockchain main stores the end-users blockchain data. It contains meta data of shared files, profile data, and social interactions.
BlockchainGlobal string `yaml:"BlockchainGlobal"` // Blockchain global caches blockchain data from global users. Empty to disable.
WarehouseMain string `yaml:"WarehouseMain"` // Warehouse main stores the actual data of files shared by the end-user.
SearchIndex string `yaml:"SearchIndex"` // Local search index of blockchain records. Empty to disable.
GeoIPDatabase string `yaml:"GeoIPDatabase"` // GeoLite2 City database to provide GeoIP information.
DataFolder string `yaml:"DataFolder"` // Data folder.
// Target for the log messages: 0 = Log file, 1 = Stdout, 2 = Log file + Stdout, 3 = None
LogTarget int `yaml:"LogTarget"`
// Listen settings
Listen []string `yaml:"Listen"` // IP:Port combinations
ListenWorkers int `yaml:"ListenWorkers"` // Count of workers to process incoming raw packets. Default 2.
ListenWorkersLite int `yaml:"ListenWorkersLite"` // Count of workers to process incoming lite packets. Default 2.
// User specific settings
PrivateKey string `yaml:"PrivateKey"` // The Private Key, hex encoded so it can be copied manually
// Initial peer seed list
SeedList []peerSeed `yaml:"SeedList"`
AutoUpdateSeedList bool `yaml:"AutoUpdateSeedList"`
SeedListVersion int `yaml:"SeedListVersion"`
// Connection settings
EnableUPnP bool `yaml:"EnableUPnP"` // Enables support for UPnP.
// PortForward specifies an external port that was manually forwarded by the user. All listening IPs must have that same port number forwarded!
// If this setting is invalid, it will prohibit other peers from connecting. If set, it automatically disables UPnP.
PortForward uint16 `yaml:"PortForward"`
// RelayFile enables forwarding Relay messages with the FILE flag: file transfers between 2 other peers that cannot establish a direct connection.
RelayFile bool `yaml:"RelayFile"`
// Global blockchain cache limits
CacheMaxBlockchainSize uint64 `yaml:"CacheMaxBlockchainSize"` // Max size of one cached blockchain in bytes.
CacheMaxSize uint64 `yaml:"CacheMaxSize"` // Max size of all cached blockchains in bytes. 0 = unlimited.
CacheMaxDownloads uint16 `yaml:"CacheMaxDownloads"` // Max count of blockchains downloaded at the same time.
}
Config defines the minimum required config for a Peernet client.
type Connection ¶
type Connection struct {
Network *Network // Network which received the packet.
Address *net.UDPAddr // Address of the remote peer.
PortInternal uint16 // Internal listening port reported by remote peer. 0 if no Announcement/Response message was yet received.
PortExternal uint16 // External listening port reported by remote peer. 0 if not known by the peer.
LastPacketIn time.Time // Last time an incoming packet was received.
LastPacketOut time.Time // Last time an outgoing packet was attempted to send.
LastPingOut time.Time // Last ping out.
Expires time.Time // Inactive connections only: Expiry date. If it does not become active by that date, it will be considered expired and removed.
Status int // 0 = Active established connection, 1 = Inactive, 2 = Removed, 3 = Redundant
RoundTripTime time.Duration // Full round-trip time of last reply.
// contains filtered or unexported fields
}
Connection is an established connection between a remote IP address and a local network adapter. New connections may only be created in case of successful INCOMING packets.
func (*Connection) Equal ¶
func (c *Connection) Equal(other *Connection) bool
Equal checks if the connection was established other the same network adapter using the same IP address. Port is intentionally not checked.
func (*Connection) IsBehindNAT ¶
func (c *Connection) IsBehindNAT() bool
IsBehindNAT checks if the remote peer on the connection is likely behind a NAT
func (*Connection) IsIPv4 ¶
func (c *Connection) IsIPv4() bool
IsIPv4 checks if the connection is using IPv4
func (*Connection) IsIPv6 ¶
func (c *Connection) IsIPv6() bool
IsIPv6 checks if the connection is using IPv6
func (*Connection) IsLocal ¶
func (c *Connection) IsLocal() bool
IsLocal checks if the connection is a local network one (LAN)
func (*Connection) IsPortForward ¶
func (c *Connection) IsPortForward() bool
IsPortForward checks if the remote peer uses port forwarding on the connection
type FileTransferStats ¶
type FileTransferStats struct {
Hash []byte // Hash of the file to transfer
Direction int // Direction of the data transfer
FileSize uint64 // File size if known
Offset uint64 // Offset to start the transfer
Limit uint64 // Limit in bytes to transfer
UDTConn *udt.UDTSocket // Underlying UDT connection
}
type Filters ¶
type Filters struct {
// NewPeer is called every time a new peer, that is one that is not currently in the peer list.
// Note that peers might be removed from peer lists and reappear quickly, i.e. this function may be called multiple times for the same peers.
// The filter must maintain its own map of unique peer IDs if actual uniqueness of new peers is desired.
NewPeer func(peer *PeerInfo, connection *Connection)
// NewPeerConnection is called for each new established connection to a peer. Note that connections might be dropped and reconnected at anytime.
NewPeerConnection func(peer *PeerInfo, connection *Connection)
// LogError is called for any error.
LogError func(function, format string, v ...interface{})
// DHTSearchStatus is called with updates of searches in the DHT. It allows to see the live progress of searches.
DHTSearchStatus func(client *dht.SearchClient, function, format string, v ...interface{})
// IncomingRequest receives all incoming request records of announcements. RequestType is the protocol.RequestX record type.
// Info is *protocol.BlockchainStore for B_STORE_BLOCKCHAIN, nil otherwise.
IncomingRequest func(peer *PeerInfo, RequestType int, Key []byte, Info interface{})
// PacketIn is a low-level filter for incoming packets after they are decrypted.
// Traverse messages are not covered.
PacketIn func(packet *protocol.PacketRaw, senderPublicKey ed25519.PublicKey, connection *Connection)
// PacketOut is a low-level filter for outgoing packets before they are encrypted.
// IPv4 broadcast, IPv6 multicast, and Traverse messages are not covered.
PacketOut func(packet *protocol.PacketRaw, receiverPublicKey ed25519.PublicKey, connection *Connection)
// MessageIn is a high-level filter for decoded incoming messages. message is of type nil, MessageAnnouncement, MessageResponse, MessageTraverse, or MessageRelay
MessageIn func(peer *PeerInfo, raw *protocol.MessageRaw, message interface{})
// MessageOutAnnouncement is a high-level filter for outgoing announcements. Peer is nil on first contact.
// Broadcast and Multicast messages are not covered.
MessageOutAnnouncement func(receiverPublicKey ed25519.PublicKey, peer *PeerInfo, packet *protocol.PacketRaw, requests *protocol.Requests)
// MessageOutResponse is a high-level filter for outgoing responses. The records are those of the whole response, which may span multiple packets.
MessageOutResponse func(peer *PeerInfo, packet *protocol.PacketRaw, records []protocol.ResponseRecord)
// MessageOutTraverse is a high-level filter for outgoing traverse messages.
MessageOutTraverse func(peer *PeerInfo, packet *protocol.PacketRaw, embeddedPacket *protocol.PacketRaw, receiverEnd ed25519.PublicKey)
// MessageOutPing is a high-level filter for outgoing pings.
MessageOutPing func(peer *PeerInfo, packet *protocol.PacketRaw, connection *Connection)
// MessageOutPong is a high-level filter for outgoing pongs.
MessageOutPong func(peer *PeerInfo, packet *protocol.PacketRaw)
// Called when the statistics change of a single blockchain in the cache. Must be set on init.
GlobalBlockchainCacheStatistic func(multi *blockchain.MultiStore, header *blockchain.MultiBlockchainHeader, statsOld blockchain.BlockchainStats)
// Called after a blockchain is deleted from the blockchain cache. The header reflects the status before deletion. Must be set on init.
GlobalBlockchainCacheDelete func(multi *blockchain.MultiStore, header *blockchain.MultiBlockchainHeader)
// BlockchainReported is called when a peer reports the version and height of its blockchain in an Announcement, Response or Local Discovery message:
// at once when the version or height changed, otherwise when the last call for the peer was 10 minutes ago or longer.
// The version and height are peer.BlockchainVersion and peer.BlockchainHeight. A blockchain is reported once its version or height is above 0.
// The blockchain cache keeps a copy of the blockchain while a reason is set for it, see BlockchainCache.Keep. It is called if the blockchain cache is enabled.
BlockchainReported func(peer *PeerInfo)
}
Filters contains all functions to install the hook. Use nil for unused. The functions are called sequentially and block execution; if the filter takes a long time it should start a Go routine.
type Network ¶
type Network struct {
sync.RWMutex // for sychronized closing
// contains filtered or unexported fields
}
Network is a connection adapter through one network interface (adapter). Note that for each IP on the same adapter separate network entries are created.
func (*Network) AutoAssignPort ¶
AutoAssignPort assigns a port for the given IP. Use port 0 for zero configuration.
func (*Network) BroadcastIPv4 ¶
BroadcastIPv4 prepares sending Broadcasts
func (*Network) BroadcastIPv4Listen ¶
func (network *Network) BroadcastIPv4Listen()
BroadcastIPv4Listen listens for incoming broadcast packets Fork from network.Listen! Keep any changes synced.
func (*Network) BroadcastIPv4Send ¶
BroadcastIPv4Send sends out a single broadcast messages to discover peers
func (*Network) GetAdapterName ¶
GetAdapterName returns the adapter name, if available
func (*Network) GetListen ¶
func (network *Network) GetListen() (listen *net.UDPAddr, multicastIPv6 net.IP, broadcastIPv4 []net.IP, ipExternal net.IP, portExternal uint16)
GetListen returns connectivity information
func (*Network) Listen ¶
func (network *Network) Listen()
Listen starts listening for incoming packets on the given UDP connection
func (*Network) MulticastIPv6Join ¶
MulticastIPv6Join joins the Multicast group
func (*Network) MulticastIPv6Listen ¶
func (network *Network) MulticastIPv6Listen()
MulticastIPv6Listen listens for incoming multicast packets Fork from network.Listen! Keep any changes synced.
func (*Network) MulticastIPv6Send ¶
MulticastIPv6Send sends out a single multicast messages to discover peers at the same site
func (*Network) SelfReportedPorts ¶
SelfReportedPorts returns the internal and external ports as self-reported by the peer to others.
type Networks ¶
type Networks struct {
// Mutex for both network lists. Higher granularity currently not needed.
sync.RWMutex
// Sequences keeps track of all message sequence number, regardless of the network connection.
Sequences *protocol.SequenceManager
// Keep track of valid IDs for lite packets.
LiteRouter *protocol.LiteRouter
// contains filtered or unexported fields
}
Networks is the collection of all connected networks
type PeerInfo ¶
type PeerInfo struct {
PublicKey ed25519.PublicKey // Public key = Peer ID. It is also the peer's key in the DHT.
sync.RWMutex // Mutex for access to list of connections.
IsRootPeer bool // Whether the peer is a trusted root peer.
UserAgent string // User Agent reported by remote peer. Empty if no Announcement/Response message was yet received.
Features uint8 // Feature bit array. 0 = IPv4_LISTEN, 1 = IPv6_LISTEN, 2 = RELAY_FILE
BlockchainHeight uint64 // Blockchain height
BlockchainVersion uint64 // Blockchain version
// statistics
StatsPacketSent uint64 // Count of packets sent
StatsPacketReceived uint64 // Count of packets received
Backend *Backend
// contains filtered or unexported fields
}
PeerInfo stores information about a single remote peer
func (*PeerInfo) BlockDownload ¶
func (peer *PeerInfo) BlockDownload(BlockchainPublicKey ed25519.PublicKey, BlockchainVersion uint64, TargetBlocks []protocol.BlockRange, callback func(data []byte, blockNumber uint64) (err error)) (height uint64, err error)
BlockDownload downloads the requested blocks of the blockchain in the given version from the remote peer. It returns the height of the blockchain that the remote peer stores. The callback is called for each block: the requested blocks below that height, in the order of the request. The blocks are not verified. The download ends if the callback returns an error.
func (*PeerInfo) BlockTransferRequest ¶
func (peer *PeerInfo) BlockTransferRequest(BlockchainPublicKey ed25519.PublicKey, BlockchainVersion uint64, TargetBlocks []protocol.BlockRange) (udtConn *udt.UDTSocket, virtualConn *VirtualPacketConn, err error)
BlockTransferRequest requests blocks of the blockchain in the given version from the peer. The peer sends the height of the blockchain that it stores, followed by the requested blocks below that height, in the order of the request. See BlockDownload for reading them. The caller must call udtConn.Close() when done. Do not use any of the closing functions of virtualConn.
func (*PeerInfo) FileTransferRequestUDT ¶
func (peer *PeerInfo) FileTransferRequestUDT(hash []byte, offset, limit uint64) (udtConn *udt.UDTSocket, virtualConn *VirtualPacketConn, err error)
FileTransferRequestUDT creates a UDT server listening for incoming data transfer via the lite protocol and requests a file transfer from a remote peer. The caller must call udtConn.Close() when done. Do not use any of the closing functions of virtualConn. Limit is optional. 0 means the entire file. A peer that is reached via a relay is requested via that relay. It fails if the relay does not set RELAY_FILE in its feature bit array.
func (*PeerInfo) GetConnection2Share ¶
func (peer *PeerInfo) GetConnection2Share(allowLocal, allowIPv4, allowIPv6 bool) (connection *Connection)
GetConnection2Share returns the preferred connection to share. Nil if none. See GetConnections2Share.
func (*PeerInfo) GetConnections ¶
func (peer *PeerInfo) GetConnections(active bool) (connections []*Connection)
GetConnections returns the list of connections
func (*PeerInfo) GetConnections2Share ¶
func (peer *PeerInfo) GetConnections2Share(allowLocal, allowIPv4, allowIPv6 bool, limit int) (connections []*Connection)
GetConnections2Share returns the connections to share in the order of preference, at most limit and one per remote address. allowLocal specifies whether it is OK to return local IPs. In that case local connections are preferred, so that peers on the same local network connect over it. The latest connection is preferred among the others. A connection via a link-local or loopback address is not shared.
func (*PeerInfo) GetRTT ¶
GetRTT returns the round-trip time for the most recent active connection. 0 if not available.
func (*PeerInfo) IsActive ¶
IsActive checks if the peer is an active peer: it is in the routing table, or a transfer with it is running. Every other peer in the peer list is a passive peer. Active peers are pinged. A passive peer stays in the peer list as long as its packets arrive.
func (*PeerInfo) IsBehindNAT ¶
IsBehindNAT checks if the peer is behind NAT
func (*PeerInfo) IsConnectable ¶
IsConnectable checks if the peer is connectable to the given IP parameters.
func (*PeerInfo) IsConnectionActive ¶
IsConnectionActive checks if the peer has an active connection that can be used to send and receive messages
func (*PeerInfo) IsPortForward ¶
IsPortForward checks if the peer uses port forwarding
type VirtualPacketConn ¶
type VirtualPacketConn struct {
Peer *PeerInfo
// Stats are maintained by the caller
Stats interface{}
sync.Mutex
// contains filtered or unexported fields
}
VirtualPacketConn is a virtual connection.
func (*VirtualPacketConn) Close ¶
func (v *VirtualPacketConn) Close(reason int) (err error)
Close provides a Close function to be called by the underlying transfer protocol. Do not call the function manually; otherwise the underlying transfer protocol may not have time to send a termination message (and the remote peer would subsequently try to reconnect). Rather, use the underlying transfer protocol's close function.
func (*VirtualPacketConn) CloseLinger ¶
func (v *VirtualPacketConn) CloseLinger(reason int) (err error)
CloseLinger is to be called by the underlying transfer protocol when it will close the socket soon after lingering around. Lingering happens to resend packets at the end of transfer, when it is not immediately known whether the remote peer received all packets.
func (*VirtualPacketConn) GetTerminateReason ¶
func (v *VirtualPacketConn) GetTerminateReason() int
GetTerminateReason returns the termination reason. 0 = Not yet terminated.
func (*VirtualPacketConn) IsTerminated ¶
func (v *VirtualPacketConn) IsTerminated() bool
IsTerminated checks if the connection is terminated
func (*VirtualPacketConn) Terminate ¶
func (v *VirtualPacketConn) Terminate(reason int) (err error)
Terminate closes the connection. Do not call this function manually. Use the underlying protocol's function to close the connection. Reason: 404 = Remote peer does not store file (upstream), 2 = Remote termination signal (upstream), 3 = Sequence invalidation or expiration (upstream), 1000+ = Transfer protocol indicated closing (downstream)
Source Files
¶
- Blockchain Announce.go
- Blockchain Cache Global.go
- Blockchain Listing.go
- Blockchain User.go
- Bootstrap.go
- Command Relay.go
- Command Traverse.go
- Commands.go
- Config.go
- Connection.go
- Exit.go
- File Formats.go
- Filter.go
- Kademlia.go
- Lock File Unix.go
- Message Send.go
- Network Detection.go
- Network IPv4 Broadcast.go
- Network IPv6 Multicast.go
- Network Init.go
- Network UPnP.go
- Network.go
- Networks.go
- Peer ID.go
- Peernet.go
- Ping.go
- Transfer Block.go
- Transfer UDT.go
- Transfer Virtual Connection.go
- Warehouse.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package reuseport provides Listen and Dial functions that set socket options in order to be able to reuse ports.
|
Package reuseport provides Listen and Dial functions that set socket options in order to be able to reuse ports. |
|
File Name: Shared Recent.go Copyright: 2021 Peernet Foundation s.r.o.
|
File Name: Shared Recent.go Copyright: 2021 Peernet Foundation s.r.o. |