enode

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 9, 2022 License: GPL-3.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ValidSchemes = enr.SchemeMap{
	"v4": V4ID{},
}

List of known secure identity schemes. 当前正常使用的所有节点标识模型

View Source
var ValidSchemesForTesting = enr.SchemeMap{
	"v4":   V4ID{},
	"null": NullID{},
}

正常使用的以及用于测试的节点标识模型

Functions

func DistCmp

func DistCmp(target, a, b ID) int

DistCmp compares the distances a->target and b->target. Returns -1 if a is closer to target, 1 if b is closer to target and 0 if they are equal. 比较节点间的距离 返回-1,a与target更近 返回1,b与target更近 返回0, a与b和target一样近

func LogDist

func LogDist(a, b ID) int

LogDist returns the logarithmic distance between a and b, log2(a ^ b). 计算a与b距离的以2为底的对数

func SignV4

func SignV4(r *enr.Record, privkey *ecdsa.PrivateKey) error

SignV4 signs a record using the v4 scheme. 使用输入的私钥对记录r签名 这个函数为Record对象增加了id,secp256k1键值对,然后调用了Record.SetSig

Types

type DB

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

DB is the node database, storing previously seen nodes and any collected metadata about them for QoS purposes.

func OpenDB

func OpenDB(path string) (*DB, error)

OpenDB opens a node database for storing and retrieving infos about known peers in the network. If no path is given an in-memory, temporary database is constructed. 创建一个储存节点的数据库对象 path为空代表创建内存数据库,否则根据路径创建持久数据库

func (*DB) Close

func (db *DB) Close()

close flushes and closes the database files. 关闭节点数据库

func (*DB) DeleteNode

func (db *DB) DeleteNode(id ID)

DeleteNode deletes all information associated with a node. 删除数据库所有和这个节点有关的信息

func (*DB) FindFails

func (db *DB) FindFails(id ID, ip net.IP) int

FindFails retrieves the number of findnode failures since bonding. 获取指定节点findfail的次数

func (*DB) FindFailsV5

func (db *DB) FindFailsV5(id ID, ip net.IP) int

FindFailsV5 retrieves the discv5 findnode failure counter. 获取指定节点findfail的次数(v5版本)

func (*DB) LastPingReceived

func (db *DB) LastPingReceived(id ID, ip net.IP) time.Time

LastPingReceived retrieves the time of the last ping packet received from a remote node. 获取指定节点的lastping时间 也就是上次接收到来自这个节点ping包的时间

func (*DB) LastPongReceived

func (db *DB) LastPongReceived(id ID, ip net.IP) time.Time

LastPongReceived retrieves the time of the last successful pong from remote node. 获取指定节点lastpong的时间 调用过LastPongReceived后,就会在后台启动删除过期节点的协程 过期节点就是超过一小时没有收到pong包的节点

func (*DB) Node

func (db *DB) Node(id ID) *Node

Node retrieves a node with a given id from the database. 输入节点ID从数据库中读取Node对象

func (*DB) NodeSeq

func (db *DB) NodeSeq(id ID) uint64

NodeSeq returns the stored record sequence number of the given node. 获取指定节点的seq

func (*DB) QuerySeeds

func (db *DB) QuerySeeds(n int, maxAge time.Duration) []*Node

QuerySeeds retrieves random nodes to be used as potential seed nodes for bootstrapping. 从数据库中随机出来最多n个节点 随机出来的节点距离上次响应时间都不超过maxAge 这个函数用于启动的时候获取初始的节点

func (*DB) Resolve

func (db *DB) Resolve(n *Node) *Node

Resolve returns the stored record of the node if it has a larger sequence number than n. 输入一个Node对象,判断输入的对象和数据库中哪个seq更大,返回seq更大的结果

func (*DB) UpdateFindFails

func (db *DB) UpdateFindFails(id ID, ip net.IP, fails int) error

UpdateFindFails updates the number of findnode failures since bonding. 更新指定节点findfail的次数

func (*DB) UpdateFindFailsV5

func (db *DB) UpdateFindFailsV5(id ID, ip net.IP, fails int) error

UpdateFindFailsV5 stores the discv5 findnode failure counter. 更新指定节点findfail的次数(V5版本)

func (*DB) UpdateLastPingReceived

func (db *DB) UpdateLastPingReceived(id ID, ip net.IP, instance time.Time) error

UpdateLastPingReceived updates the last time we tried contacting a remote node. 更新指定节点的lastping时间 更新上次接收到来自这个节点ping包的时间为指定的时间

func (*DB) UpdateLastPongReceived

func (db *DB) UpdateLastPongReceived(id ID, ip net.IP, instance time.Time) error

UpdateLastPongReceived updates the last pong time of a node. 更新指定节点lastpong的时间

func (*DB) UpdateNode

func (db *DB) UpdateNode(node *Node) error

UpdateNode inserts - potentially overwriting - a node into the peer database. 将输入的节点保存到数据库中 输入的节点的Seq要大于数据库中存在的 每个节点在数据库中占用两个字段

nodeKey(node.ID())用来保存节点的rlp编码
nodeItemKey(node.ID(),zeroIP,dbNodeSeq)保存节点的Seq

type FairMix

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

FairMix aggregates multiple node iterators. The mixer itself is an iterator which ends only when Close is called. Source iterators added via AddSource are removed from the mix when they end.

The distribution of nodes returned by Next is approximately fair, i.e. FairMix attempts to draw from all sources equally often. However, if a certain source is slow and doesn't return a node within the configured timeout, a node from any other source will be returned.

It's safe to call AddSource and Close concurrently with Next. 可以以公平的方式从多个来源迭代节点

func NewFairMix

func NewFairMix(timeout time.Duration) *FairMix

NewFairMix creates a mixer.

The timeout specifies how long the mixer will wait for the next fairly-chosen source before giving up and taking a node from any other source. A good way to set the timeout is deciding how long you'd want to wait for a node on average. Passing a negative timeout makes the mixer completely fair. 创建一个FairMix迭代器,用来从多个来源平均的迭代节点 输入的时间表示等待一个来源返回节点的超时时间

func (*FairMix) AddSource

func (m *FairMix) AddSource(it Iterator)

AddSource adds a source of nodes. AddSource就是在FairMix.sources数组中添加一项,并且启动这个来源的协程

func (*FairMix) Close

func (m *FairMix) Close()

Close shuts down the mixer and all current sources. Calling this is required to release resources associated with the mixer.

func (*FairMix) Next

func (m *FairMix) Next() bool

Next returns a node from a random source. 迭代下一个节点 默认从下一个来源中读取节点,如果下一个来源等待时间超时那么就从所有来源中读取一个

func (*FairMix) Node

func (m *FairMix) Node() *Node

Node returns the current node.

type ID

type ID [32]byte

ID is a unique identifier for each node. ID是每个节点的唯一标识,本质是长度32字节的字节数组

func HexID

func HexID(in string) ID

HexID converts a hex string to an ID. The string may be prefixed with 0x. It panics if the string is not a valid ID. 将hex字符串解析为ID,格式错误将会panic hex字符串有无0x前缀皆可

func ParseID

func ParseID(in string) (ID, error)

将hex字符串转化成enode.ID对象

func PubkeyToIDV4

func PubkeyToIDV4(key *ecdsa.PublicKey) ID

PubkeyToIDV4 derives the v4 node address from the given public key. 将公钥转换成节点ID 计算方法: keccak256(pub.X || pub.Y)

func (ID) Bytes

func (n ID) Bytes() []byte

Bytes returns a byte slice representation of the ID

func (ID) GoString

func (n ID) GoString() string

The Go syntax representation of a ID is a call to HexID.

func (ID) MarshalText

func (n ID) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (ID) String

func (n ID) String() string

ID prints as a long hexadecimal number. 将id转换成hex字符串

func (ID) TerminalString

func (n ID) TerminalString() string

TerminalString returns a shortened hex string for terminal logging.

func (*ID) UnmarshalText

func (n *ID) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. 从hex字符串转化成enode.ID对象,text是hex字符串的字节数组

type Iterator

type Iterator interface {
	Next() bool  // moves to next node
	Node() *Node // returns current node
	Close()      // ends the iterator
}

Iterator represents a sequence of nodes. The Next method moves to the next node in the sequence. It returns false when the sequence has ended or the iterator is closed. Close may be called concurrently with Next and Node, and interrupts Next if it is blocked. 节点的迭代器对象,包含Next,Node,Close方法 这个文件实现了sliceIter,filterIter,FairMix

func CycleNodes

func CycleNodes(nodes []*Node) Iterator

CycleNodes makes an iterator which cycles through the given nodes indefinitely. 生成一个在输入的这些节点中遍历的迭代器,迭代到结尾就重新从头开始,可以无限迭代

func Filter

func Filter(it Iterator, check func(*Node) bool) Iterator

Filter wraps an iterator such that Next only returns nodes for which the 'check' function returns true. 对已有的迭代器进行封装,只迭代满足check函数的节点

func IterNodes

func IterNodes(nodes []*Node) Iterator

IterNodes makes an iterator which runs through the given nodes once. 生成一个在输入的这些节点中遍历的迭代器,迭代到结尾就结束

type LocalNode

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

LocalNode produces the signed node record of a local node, i.e. a node run in the current process. Setting ENR entries via the Set method updates the record. A new version of the record is signed on demand when the Node method is called. LocalNode对象用于生成本地节点经过签名的Record对象

func NewLocalNode

func NewLocalNode(db *DB, key *ecdsa.PrivateKey) *LocalNode

NewLocalNode creates a local node. 创建一个本地节点,指定节点数据库和本地节点的私钥

func (*LocalNode) Database

func (ln *LocalNode) Database() *DB

Database returns the node database associated with the local node. 获取本地节点使用的数据库

func (*LocalNode) Delete

func (ln *LocalNode) Delete(e enr.Entry)

Delete removes the given entry from the local record. 从LocalNode.entries删除一项,同样删除后也需要重新签名

func (*LocalNode) ID

func (ln *LocalNode) ID() ID

ID returns the local node ID.

func (*LocalNode) Node

func (ln *LocalNode) Node() *Node

Node returns the current version of the local node record. 将本地节点转换为Node对象

func (*LocalNode) Seq

func (ln *LocalNode) Seq() uint64

Seq returns the current sequence number of the local node record.

func (*LocalNode) Set

func (ln *LocalNode) Set(e enr.Entry)

Set puts the given entry into the local record, overwriting any existing value. Use Set*IP and SetFallbackUDP to set IP addresses and UDP port, otherwise they'll be overwritten by the endpoint predictor.

Since node record updates are throttled to one per second, Set is asynchronous. Any update will be queued up and published when at least one second passes from the last change. 往LocalNode.entries字段一条 ENRKey->Entry 的映射 并且添加后使得缓存的cur失效,因为增加了新的键值对要重新签名

func (*LocalNode) SetFallbackIP

func (ln *LocalNode) SetFallbackIP(ip net.IP)

SetFallbackIP sets the last-resort IP address. This address is used if no endpoint prediction can be made and no static IP is set. 设置LocalNode.endpoint4或LocalNode.endpoint6 的fallbackIP字段 fallbackIP是没有预测结果而且静态ip也没有设置的最终结果

func (*LocalNode) SetFallbackUDP

func (ln *LocalNode) SetFallbackUDP(port int)

SetFallbackUDP sets the last-resort UDP-on-IPv4 port. This port is used if no endpoint prediction can be made. 设置ln.endpoint4和ln.endpoint6的fallbackUDP字段

func (*LocalNode) SetStaticIP

func (ln *LocalNode) SetStaticIP(ip net.IP)

SetStaticIP sets the local IP to the given one unconditionally. This disables endpoint prediction. 设置LocalNode的staticIP字段

func (*LocalNode) UDPContact

func (ln *LocalNode) UDPContact(toaddr *net.UDPAddr)

UDPContact should be called whenever the local node has announced itself to another node via UDP. It feeds the local endpoint predictor. 一旦本地向其他节点发送Ping包,就调用AddContact往IPTracker里面添加

func (*LocalNode) UDPEndpointStatement

func (ln *LocalNode) UDPEndpointStatement(fromaddr, endpoint *net.UDPAddr)

UDPEndpointStatement should be called whenever a statement about the local node's UDP endpoint is received. It feeds the local endpoint predictor. fromaddr代表其他节点的地址,endpoint代表fromaddr认为本地的地址 一旦获得了别的节点认为本地节点的地址的信息就调用此方法 v4版本节点发现收到ping和pong都会调用 v5版本节点发现收到pong包会调用

type Node

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

Node represents a host on the network.

func MustParse

func MustParse(rawurl string) *Node

MustParse parses a node record or enode:// URL. It panics if the input is invalid.

func MustParseV4

func MustParseV4(rawurl string) *Node

MustParseV4 parses a node URL. It panics if the URL is not valid.

func New

func New(validSchemes enr.IdentityScheme, r *enr.Record) (*Node, error)

New wraps a node record. The record must be valid according to the given identity scheme. 新建一个Node对象, node.id就是IdentityScheme.NodeAddr的返回值 输入的Record必须满足给定的scheme

func NewV4

func NewV4(pubkey *ecdsa.PublicKey, ip net.IP, tcp, udp int) *Node

NewV4 creates a node from discovery v4 node information. The record contained in the node has a zero-length signature. 创建一个v4版本的节点对象 需要提供节点的公钥,ip,tcp和udp端口

func Parse

func Parse(validSchemes enr.IdentityScheme, input string) (*Node, error)

Parse decodes and verifies a base64-encoded node record. 解析节点链接 输入的格式可能是:

enode://xxx
enr:xxx

创建两种类型的节点真实函数是New和NewV4 分别用来创建enr类型和enode类型

func ParseV4

func ParseV4(rawurl string) (*Node, error)

ParseV4 parses a node URL.

There are two basic forms of node URLs:

  • incomplete nodes, which only have the public key (node ID)
  • complete nodes, which contain the public key and IP/Port information

For incomplete nodes, the designator must look like one of these

enode://<hex node id>
<hex node id>

For complete nodes, the node ID is encoded in the username portion of the URL, separated from the host by an @ sign. The hostname can only be given as an IP address or using DNS domain name. The port in the host name section is the TCP listening port. If the TCP and UDP (discovery) ports differ, the UDP port is specified as query parameter "discport".

In the following example, the node URL describes a node with IP address 10.3.58.6, TCP listening port 30303 and UDP discovery port 30301.

enode://<hex node id>@10.3.58.6:30303?discport=30301

解析V4版本的链接,有两种类型,不完整版和完整版 不完整版的格式如下

enode://<hex node id>
<hex node id>

完整版的格式包括了ip以及端口号,例如

enode://<hex node id>@10.3.58.6:30303?discport=30301

func ReadNodes

func ReadNodes(it Iterator, n int) []*Node

ReadNodes reads at most n nodes from the given iterator. The return value contains no duplicates and no nil values. To prevent looping indefinitely for small repeating node sequences, this function calls Next at most n times. 从迭代器中读取n个节点,并对结果进行去重,读取过程中迭代器到底直接返回

func SignNull

func SignNull(r *enr.Record, id ID) *Node

func (*Node) ID

func (n *Node) ID() ID

ID returns the node identifier.

func (*Node) IP

func (n *Node) IP() net.IP

IP returns the IP address of the node. This prefers IPv4 addresses.

func (*Node) Incomplete

func (n *Node) Incomplete() bool

Incomplete returns true for nodes with no IP address. 如果节点没有ip地址这个就返回true

func (*Node) Load

func (n *Node) Load(k enr.Entry) error

Load retrieves an entry from the underlying record.

func (*Node) MarshalText

func (n *Node) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*Node) Pubkey

func (n *Node) Pubkey() *ecdsa.PublicKey

Pubkey returns the secp256k1 public key of the node, if present.

func (*Node) Record

func (n *Node) Record() *enr.Record

Record returns the node's record. The return value is a copy and may be modified by the caller.

func (*Node) Seq

func (n *Node) Seq() uint64

Seq returns the sequence number of the underlying record.

func (*Node) String

func (n *Node) String() string

String returns the text representation of the record. 将节点对象还原成原来的链接

func (*Node) TCP

func (n *Node) TCP() int

TCP returns the TCP port of the node.

func (*Node) UDP

func (n *Node) UDP() int

UDP returns the UDP port of the node.

func (*Node) URLv4

func (n *Node) URLv4() string

构造enode链接

func (*Node) UnmarshalText

func (n *Node) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

func (*Node) ValidateComplete

func (n *Node) ValidateComplete() error

ValidateComplete checks whether n has a valid IP and UDP port. Deprecated: don't use this method. 确保节点保存了ip和udp端口以及节点公钥

type NullID

type NullID struct{}

NullID is the "null" ENR identity scheme. This scheme stores the node ID in the record without any signature. 不进行签名,节点的地址就是SignNull传入的id

func (NullID) NodeAddr

func (NullID) NodeAddr(r *enr.Record) []byte

func (NullID) Verify

func (NullID) Verify(r *enr.Record, sig []byte) error

type Secp256k1

type Secp256k1 ecdsa.PublicKey

Secp256k1 is the "secp256k1" key, which holds a public key. 代表键值对中的公钥键值对 公钥在记录中是以压缩格式保存

func (*Secp256k1) DecodeRLP

func (v *Secp256k1) DecodeRLP(s *rlp.Stream) error

DecodeRLP implements rlp.Decoder. 解码rlp编码,将解析出来的内容进行解压

func (Secp256k1) ENRKey

func (v Secp256k1) ENRKey() string

func (Secp256k1) EncodeRLP

func (v Secp256k1) EncodeRLP(w io.Writer) error

EncodeRLP implements rlp.Encoder. 对公钥压缩后进行rlp编码

type V4ID

type V4ID struct{}

v4ID is the "v4" identity scheme.

func (V4ID) NodeAddr

func (V4ID) NodeAddr(r *enr.Record) []byte

利用节点记录enr.Record对象,计算出节点ID 节点ID计算规则: keccak256(pub.X || pub.Y) 节点地址就是将公钥的X,Y拼在一起变成64字节的buf,然后对buf求哈希

func (V4ID) Verify

func (V4ID) Verify(r *enr.Record, sig []byte) error

验证enr.Record对象的签名 用于实现IdentityScheme接口

Jump to

Keyboard shortcuts

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