p2p: golint fixes

This commit is contained in:
Mike Kinney 2019-12-10 07:03:34 -08:00
parent d90d1db609
commit b451352aff
26 changed files with 151 additions and 76 deletions

View file

@ -67,12 +67,12 @@ const (
// RPC packet types // RPC packet types
const ( const (
p_pingV4 = iota + 1 // zero is 'reserved' pPingV4 = iota + 1 // zero is 'reserved'
p_pongV4 pPongV4
p_findnodeV4 pFindnodeV4
p_neighborsV4 pNeighborsV4
p_enrRequestV4 pEnrRequestV4
p_enrResponseV4 pEnrResponseV4
) )
// RPC request structures // RPC request structures
@ -257,6 +257,7 @@ type reply struct {
matched chan<- bool matched chan<- bool
} }
// ListenV4 will create a udp listener
func ListenV4(c UDPConn, ln *enode.LocalNode, cfg Config) (*UDPv4, error) { func ListenV4(c UDPConn, ln *enode.LocalNode, cfg Config) (*UDPv4, error) {
closeCtx, cancel := context.WithCancel(context.Background()) closeCtx, cancel := context.WithCancel(context.Background())
t := &UDPv4{ t := &UDPv4{
@ -366,7 +367,7 @@ func (t *UDPv4) sendPing(toid enode.ID, toaddr *net.UDPAddr, callback func()) *r
} }
// Add a matcher for the reply to the pending reply queue. Pongs are matched if they // Add a matcher for the reply to the pending reply queue. Pongs are matched if they
// reference the ping we're about to send. // reference the ping we're about to send.
rm := t.pending(toid, toaddr.IP, p_pongV4, func(p interface{}) (matched bool, requestDone bool) { rm := t.pending(toid, toaddr.IP, pPongV4, func(p interface{}) (matched bool, requestDone bool) {
matched = bytes.Equal(p.(*pongV4).ReplyTok, hash) matched = bytes.Equal(p.(*pongV4).ReplyTok, hash)
if matched && callback != nil { if matched && callback != nil {
callback() callback()
@ -438,7 +439,7 @@ func (t *UDPv4) findnode(toid enode.ID, toaddr *net.UDPAddr, target encPubkey) (
// active until enough nodes have been received. // active until enough nodes have been received.
nodes := make([]*node, 0, bucketSize) nodes := make([]*node, 0, bucketSize)
nreceived := 0 nreceived := 0
rm := t.pending(toid, toaddr.IP, p_neighborsV4, func(r interface{}) (matched bool, requestDone bool) { rm := t.pending(toid, toaddr.IP, pNeighborsV4, func(r interface{}) (matched bool, requestDone bool) {
reply := r.(*neighborsV4) reply := r.(*neighborsV4)
for _, rn := range reply.Nodes { for _, rn := range reply.Nodes {
nreceived++ nreceived++
@ -472,7 +473,7 @@ func (t *UDPv4) RequestENR(n *enode.Node) (*enode.Node, error) {
} }
// Add a matcher for the reply to the pending reply queue. Responses are matched if // Add a matcher for the reply to the pending reply queue. Responses are matched if
// they reference the request we're about to send. // they reference the request we're about to send.
rm := t.pending(n.ID(), addr.IP, p_enrResponseV4, func(r interface{}) (matched bool, requestDone bool) { rm := t.pending(n.ID(), addr.IP, pEnrResponseV4, func(r interface{}) (matched bool, requestDone bool) {
matched = bytes.Equal(r.(*enrResponseV4).ReplyTok, hash) matched = bytes.Equal(r.(*enrResponseV4).ReplyTok, hash)
return matched, matched return matched, matched
}) })
@ -752,17 +753,17 @@ func decodeV4(buf []byte) (packetV4, encPubkey, []byte, error) {
var req packetV4 var req packetV4
switch ptype := sigdata[0]; ptype { switch ptype := sigdata[0]; ptype {
case p_pingV4: case pPingV4:
req = new(pingV4) req = new(pingV4)
case p_pongV4: case pPongV4:
req = new(pongV4) req = new(pongV4)
case p_findnodeV4: case pFindnodeV4:
req = new(findnodeV4) req = new(findnodeV4)
case p_neighborsV4: case pNeighborsV4:
req = new(neighborsV4) req = new(neighborsV4)
case p_enrRequestV4: case pEnrRequestV4:
req = new(enrRequestV4) req = new(enrRequestV4)
case p_enrResponseV4: case pEnrResponseV4:
req = new(enrResponseV4) req = new(enrResponseV4)
default: default:
return nil, fromKey, hash, fmt.Errorf("unknown type: %d", ptype) return nil, fromKey, hash, fmt.Errorf("unknown type: %d", ptype)
@ -806,7 +807,7 @@ func seqFromTail(tail []rlp.RawValue) uint64 {
// PING/v4 // PING/v4
func (req *pingV4) name() string { return "PING/v4" } func (req *pingV4) name() string { return "PING/v4" }
func (req *pingV4) kind() byte { return p_pingV4 } func (req *pingV4) kind() byte { return pPingV4 }
func (req *pingV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error { func (req *pingV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
if expired(req.Expiration) { if expired(req.Expiration) {
@ -848,7 +849,7 @@ func (req *pingV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []by
// PONG/v4 // PONG/v4
func (req *pongV4) name() string { return "PONG/v4" } func (req *pongV4) name() string { return "PONG/v4" }
func (req *pongV4) kind() byte { return p_pongV4 } func (req *pongV4) kind() byte { return pPongV4 }
func (req *pongV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error { func (req *pongV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
if expired(req.Expiration) { if expired(req.Expiration) {
@ -868,7 +869,7 @@ func (req *pongV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac []by
// FINDNODE/v4 // FINDNODE/v4
func (req *findnodeV4) name() string { return "FINDNODE/v4" } func (req *findnodeV4) name() string { return "FINDNODE/v4" }
func (req *findnodeV4) kind() byte { return p_findnodeV4 } func (req *findnodeV4) kind() byte { return pFindnodeV4 }
func (req *findnodeV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error { func (req *findnodeV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
if expired(req.Expiration) { if expired(req.Expiration) {
@ -915,7 +916,7 @@ func (req *findnodeV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac
// NEIGHBORS/v4 // NEIGHBORS/v4
func (req *neighborsV4) name() string { return "NEIGHBORS/v4" } func (req *neighborsV4) name() string { return "NEIGHBORS/v4" }
func (req *neighborsV4) kind() byte { return p_neighborsV4 } func (req *neighborsV4) kind() byte { return pNeighborsV4 }
func (req *neighborsV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error { func (req *neighborsV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
if expired(req.Expiration) { if expired(req.Expiration) {
@ -933,7 +934,7 @@ func (req *neighborsV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, mac
// ENRREQUEST/v4 // ENRREQUEST/v4
func (req *enrRequestV4) name() string { return "ENRREQUEST/v4" } func (req *enrRequestV4) name() string { return "ENRREQUEST/v4" }
func (req *enrRequestV4) kind() byte { return p_enrRequestV4 } func (req *enrRequestV4) kind() byte { return pEnrRequestV4 }
func (req *enrRequestV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error { func (req *enrRequestV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
if expired(req.Expiration) { if expired(req.Expiration) {
@ -955,7 +956,7 @@ func (req *enrRequestV4) handle(t *UDPv4, from *net.UDPAddr, fromID enode.ID, ma
// ENRRESPONSE/v4 // ENRRESPONSE/v4
func (req *enrResponseV4) name() string { return "ENRRESPONSE/v4" } func (req *enrResponseV4) name() string { return "ENRRESPONSE/v4" }
func (req *enrResponseV4) kind() byte { return p_enrResponseV4 } func (req *enrResponseV4) kind() byte { return pEnrResponseV4 }
func (req *enrResponseV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error { func (req *enrResponseV4) preverify(t *UDPv4, from *net.UDPAddr, fromID enode.ID, fromKey encPubkey) error {
if !t.handleReply(fromID, from.IP, req) { if !t.handleReply(fromID, from.IP, req) {

View file

@ -251,7 +251,7 @@ func (n NodeID) String() string {
return fmt.Sprintf("%x", n[:]) return fmt.Sprintf("%x", n[:])
} }
// The Go syntax representation of a NodeID is a call to HexID. // GoString returns the Go syntax representation of a NodeID which is a call to HexID.
func (n NodeID) GoString() string { func (n NodeID) GoString() string {
return fmt.Sprintf("discover.HexID(\"%x\")", n[:]) return fmt.Sprintf("discover.HexID(\"%x\")", n[:])
} }

View file

@ -37,6 +37,7 @@ const (
maxFindnodeFailures = 5 maxFindnodeFailures = 5
) )
// Table is a struct that holds the nodes/peers
type Table struct { type Table struct {
count int // number of nodes count int // number of nodes
buckets [nBuckets]*bucket // index of known nodes by distance buckets [nBuckets]*bucket // index of known nodes by distance

View file

@ -625,7 +625,7 @@ func (b *topicRadiusBucket) update(now mclock.AbsTime) {
for target, tm := range b.lookupSent { for target, tm := range b.lookupSent {
if now-tm > mclock.AbsTime(respTimeout) { if now-tm > mclock.AbsTime(respTimeout) {
b.weights[trNoAdjust] += 1 b.weights[trNoAdjust]++
delete(b.lookupSent, target) delete(b.lookupSent, target)
} }
} }
@ -634,10 +634,10 @@ func (b *topicRadiusBucket) update(now mclock.AbsTime) {
func (b *topicRadiusBucket) adjust(now mclock.AbsTime, inside float64) { func (b *topicRadiusBucket) adjust(now mclock.AbsTime, inside float64) {
b.update(now) b.update(now)
if inside <= 0 { if inside <= 0 {
b.weights[trOutside] += 1 b.weights[trOutside]++
} else { } else {
if inside >= 1 { if inside >= 1 {
b.weights[trInside] += 1 b.weights[trInside]++
} else { } else {
b.weights[trInside] += inside b.weights[trInside] += inside
b.weights[trOutside] += 1 - inside b.weights[trOutside] += 1 - inside

View file

@ -28,17 +28,18 @@ import (
"golang.org/x/crypto/sha3" "golang.org/x/crypto/sha3"
) )
// List of known secure identity schemes. // ValidSchemes is a list of known secure identity schemes.
var ValidSchemes = enr.SchemeMap{ var ValidSchemes = enr.SchemeMap{
"v4": V4ID{}, "v4": V4ID{},
} }
// ValidSchemesForTesting is a list of security identity schemes used in testing
var ValidSchemesForTesting = enr.SchemeMap{ var ValidSchemesForTesting = enr.SchemeMap{
"v4": V4ID{}, "v4": V4ID{},
"null": NullID{}, "null": NullID{},
} }
// v4ID is the "v4" identity scheme. // V4ID is the "v4" identity scheme.
type V4ID struct{} type V4ID struct{}
// SignV4 signs a record using the v4 scheme. // SignV4 signs a record using the v4 scheme.
@ -61,6 +62,7 @@ func SignV4(r *enr.Record, privkey *ecdsa.PrivateKey) error {
return err return err
} }
// Verify verifies a record using the v4 scheme.
func (V4ID) Verify(r *enr.Record, sig []byte) error { func (V4ID) Verify(r *enr.Record, sig []byte) error {
var entry s256raw var entry s256raw
if err := r.Load(&entry); err != nil { if err := r.Load(&entry); err != nil {
@ -77,6 +79,7 @@ func (V4ID) Verify(r *enr.Record, sig []byte) error {
return nil return nil
} }
// NodeAddr returns the node address from a record
func (V4ID) NodeAddr(r *enr.Record) []byte { func (V4ID) NodeAddr(r *enr.Record) []byte {
var pubkey Secp256k1 var pubkey Secp256k1
err := r.Load(&pubkey) err := r.Load(&pubkey)
@ -92,6 +95,7 @@ func (V4ID) NodeAddr(r *enr.Record) []byte {
// Secp256k1 is the "secp256k1" key, which holds a public key. // Secp256k1 is the "secp256k1" key, which holds a public key.
type Secp256k1 ecdsa.PublicKey type Secp256k1 ecdsa.PublicKey
// ENRKey returns the ENR identiy scheme string
func (v Secp256k1) ENRKey() string { return "secp256k1" } func (v Secp256k1) ENRKey() string { return "secp256k1" }
// EncodeRLP implements rlp.Encoder. // EncodeRLP implements rlp.Encoder.
@ -116,6 +120,7 @@ func (v *Secp256k1) DecodeRLP(s *rlp.Stream) error {
// s256raw is an unparsed secp256k1 public key entry. // s256raw is an unparsed secp256k1 public key entry.
type s256raw []byte type s256raw []byte
// ENRKey returns the ENR identiy scheme string
func (s256raw) ENRKey() string { return "secp256k1" } func (s256raw) ENRKey() string { return "secp256k1" }
// v4CompatID is a weaker and insecure version of the "v4" scheme which only checks for the // v4CompatID is a weaker and insecure version of the "v4" scheme which only checks for the
@ -140,16 +145,19 @@ func signV4Compat(r *enr.Record, pubkey *ecdsa.PublicKey) {
// ID in the record without any signature. // ID in the record without any signature.
type NullID struct{} type NullID struct{}
// Verify on a NullID is a noop. It is just for testing purposes.
func (NullID) Verify(r *enr.Record, sig []byte) error { func (NullID) Verify(r *enr.Record, sig []byte) error {
return nil return nil
} }
// NodeAddr returns the node address from a record
func (NullID) NodeAddr(r *enr.Record) []byte { func (NullID) NodeAddr(r *enr.Record) []byte {
var id ID var id ID
r.Load(enr.WithEntry("nulladdr", &id)) r.Load(enr.WithEntry("nulladdr", &id))
return id[:] return id[:]
} }
// SignNull will set an ENR identiy record with a null id
func SignNull(r *enr.Record, id ID) *Node { func SignNull(r *enr.Record, id ID) *Node {
r.Set(enr.ID("null")) r.Set(enr.ID("null"))
r.Set(enr.WithEntry("nulladdr", id)) r.Set(enr.WithEntry("nulladdr", id))

View file

@ -122,7 +122,7 @@ func (n *Node) UDP() int {
return int(port) return int(port)
} }
// UDP returns the TCP port of the node. // TCP returns the TCP port of the node.
func (n *Node) TCP() int { func (n *Node) TCP() int {
var port enr.TCP var port enr.TCP
n.Load(&port) n.Load(&port)
@ -200,7 +200,7 @@ func (n ID) String() string {
return fmt.Sprintf("%x", n[:]) return fmt.Sprintf("%x", n[:])
} }
// The Go syntax representation of a ID is a call to HexID. // GoString returns the Go syntax representation of a ID which is a call to HexID.
func (n ID) GoString() string { func (n ID) GoString() string {
return fmt.Sprintf("enode.HexID(\"%x\")", n[:]) return fmt.Sprintf("enode.HexID(\"%x\")", n[:])
} }

View file

@ -440,7 +440,7 @@ func nextNode(it iterator.Iterator) *Node {
return nil return nil
} }
// close flushes and closes the database files. // Close flushes and closes the database files.
func (db *DB) Close() { func (db *DB) Close() {
close(db.quit) close(db.quit)
db.lvl.Close() db.lvl.Close()

View file

@ -43,9 +43,11 @@ import (
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
) )
const SizeLimit = 300 // maximum encoded size of a node record in bytes // SizeLimit is the maximum encoded size of a node record in bytes
const SizeLimit = 300
var ( var (
// ErrInvalidSig is an invalid signature on node record error
ErrInvalidSig = errors.New("invalid signature on node record") ErrInvalidSig = errors.New("invalid signature on node record")
errNotSorted = errors.New("record key/value pairs are not sorted by key") errNotSorted = errors.New("record key/value pairs are not sorted by key")
errDuplicateKey = errors.New("record contains duplicate key") errDuplicateKey = errors.New("record contains duplicate key")
@ -65,6 +67,7 @@ type IdentityScheme interface {
// SchemeMap is a registry of named identity schemes. // SchemeMap is a registry of named identity schemes.
type SchemeMap map[string]IdentityScheme type SchemeMap map[string]IdentityScheme
// Verify will verify a record
func (m SchemeMap) Verify(r *Record, sig []byte) error { func (m SchemeMap) Verify(r *Record, sig []byte) error {
s := m[r.IdentityScheme()] s := m[r.IdentityScheme()]
if s == nil { if s == nil {
@ -73,6 +76,7 @@ func (m SchemeMap) Verify(r *Record, sig []byte) error {
return s.Verify(r, sig) return s.Verify(r, sig)
} }
// NodeAddr returns the node address of record
func (m SchemeMap) NodeAddr(r *Record) []byte { func (m SchemeMap) NodeAddr(r *Record) []byte {
s := m[r.IdentityScheme()] s := m[r.IdentityScheme()]
if s == nil { if s == nil {

View file

@ -58,28 +58,34 @@ func WithEntry(k string, v interface{}) Entry {
// TCP is the "tcp" key, which holds the TCP port of the node. // TCP is the "tcp" key, which holds the TCP port of the node.
type TCP uint16 type TCP uint16
// ENRKey returns the string representation of the key
func (v TCP) ENRKey() string { return "tcp" } func (v TCP) ENRKey() string { return "tcp" }
// UDP is the "udp" key, which holds the IPv6-specific UDP port of the node. // TCP6 is the "udp" key, which holds the IPv6-specific UDP port of the node.
type TCP6 uint16 type TCP6 uint16
// ENRKey returns the string representation of the key
func (v TCP6) ENRKey() string { return "tcp6" } func (v TCP6) ENRKey() string { return "tcp6" }
// UDP is the "udp" key, which holds the UDP port of the node. // UDP is the "udp" key, which holds the UDP port of the node.
type UDP uint16 type UDP uint16
// ENRKey returns the string representation of the key
func (v UDP) ENRKey() string { return "udp" } func (v UDP) ENRKey() string { return "udp" }
// UDP is the "udp" key, which holds the IPv6-specific UDP port of the node. // UDP6 is the "udp" key, which holds the IPv6-specific UDP port of the node.
type UDP6 uint16 type UDP6 uint16
// ENRKey returns the string representation of the key
func (v UDP6) ENRKey() string { return "udp6" } func (v UDP6) ENRKey() string { return "udp6" }
// ID is the "id" key, which holds the name of the identity scheme. // ID is the "id" key, which holds the name of the identity scheme.
type ID string type ID string
const IDv4 = ID("v4") // the default identity scheme // IDv4 is the default identity scheme
const IDv4 = ID("v4")
// ENRKey returns the string representation of the key
func (v ID) ENRKey() string { return "id" } func (v ID) ENRKey() string { return "id" }
// IP is either the "ip" or "ip6" key, depending on the value. // IP is either the "ip" or "ip6" key, depending on the value.
@ -87,6 +93,7 @@ func (v ID) ENRKey() string { return "id" }
// To load an address from a record use the IPv4 or IPv6 types. // To load an address from a record use the IPv4 or IPv6 types.
type IP net.IP type IP net.IP
// ENRKey returns the string representation of the key
func (v IP) ENRKey() string { func (v IP) ENRKey() string {
if net.IP(v).To4() == nil { if net.IP(v).To4() == nil {
return "ip6" return "ip6"
@ -119,6 +126,7 @@ func (v *IP) DecodeRLP(s *rlp.Stream) error {
// IPv4 is the "ip" key, which holds the IP address of the node. // IPv4 is the "ip" key, which holds the IP address of the node.
type IPv4 net.IP type IPv4 net.IP
// ENRKey returns the string representation of the key
func (v IPv4) ENRKey() string { return "ip" } func (v IPv4) ENRKey() string { return "ip" }
// EncodeRLP implements rlp.Encoder. // EncodeRLP implements rlp.Encoder.
@ -144,6 +152,7 @@ func (v *IPv4) DecodeRLP(s *rlp.Stream) error {
// IPv6 is the "ip6" key, which holds the IP address of the node. // IPv6 is the "ip6" key, which holds the IP address of the node.
type IPv6 net.IP type IPv6 net.IP
// ENRKey returns the string representation of the key
func (v IPv6) ENRKey() string { return "ip6" } func (v IPv6) ENRKey() string { return "ip6" }
// EncodeRLP implements rlp.Encoder. // EncodeRLP implements rlp.Encoder.

View file

@ -70,10 +70,12 @@ func (msg Msg) Discard() error {
return err return err
} }
// MsgReader provides reading of encoded messages
type MsgReader interface { type MsgReader interface {
ReadMsg() (Msg, error) ReadMsg() (Msg, error)
} }
// MsgWriter provides reading of encoded messages
type MsgWriter interface { type MsgWriter interface {
// WriteMsg sends a message. It will block until the message's // WriteMsg sends a message. It will block until the message's
// Payload has been consumed by the other end. // Payload has been consumed by the other end.

View file

@ -30,12 +30,17 @@ import (
) )
const ( const (
MetricsInboundTraffic = "p2p/ingress" // Name for the registered inbound traffic meter // MetricsInboundTraffic is the name for the registered inbound traffic meter
MetricsOutboundTraffic = "p2p/egress" // Name for the registered outbound traffic meter MetricsInboundTraffic = "p2p/ingress"
MetricsOutboundConnects = "p2p/dials" // Name for the registered outbound connects meter // MetricsOutboundTraffic is the name for the registered outbound traffic meter
MetricsInboundConnects = "p2p/serves" // Name for the registered inbound connects meter MetricsOutboundTraffic = "p2p/egress"
// MetricsOutboundConnects is the name for the registered outbound connects meter
MetricsOutboundConnects = "p2p/dials"
// MetricsInboundConnects is the name for the registered inbound connects meter
MetricsInboundConnects = "p2p/serves"
MeteredPeerLimit = 1024 // This amount of peers are individually metered // MeteredPeerLimit is the amount of peers are individually metered
MeteredPeerLimit = 1024
) )
var ( var (
@ -45,8 +50,10 @@ var (
egressTrafficMeter = metrics.NewRegisteredMeter(MetricsOutboundTraffic, nil) // Meter metering the cumulative egress traffic egressTrafficMeter = metrics.NewRegisteredMeter(MetricsOutboundTraffic, nil) // Meter metering the cumulative egress traffic
activePeerGauge = metrics.NewRegisteredGauge("p2p/peers", nil) // Gauge tracking the current peer count activePeerGauge = metrics.NewRegisteredGauge("p2p/peers", nil) // Gauge tracking the current peer count
PeerIngressRegistry = metrics.NewPrefixedChildRegistry(metrics.EphemeralRegistry, MetricsInboundTraffic+"/") // Registry containing the peer ingress // PeerIngressRegistry is a registry containing the peer ingress
PeerEgressRegistry = metrics.NewPrefixedChildRegistry(metrics.EphemeralRegistry, MetricsOutboundTraffic+"/") // Registry containing the peer egress PeerIngressRegistry = metrics.NewPrefixedChildRegistry(metrics.EphemeralRegistry, MetricsInboundTraffic+"/")
// PeerEgressRegistry is a registry containing the peer egress
PeerEgressRegistry = metrics.NewPrefixedChildRegistry(metrics.EphemeralRegistry, MetricsOutboundTraffic+"/")
meteredPeerFeed event.Feed // Event feed for peer metrics meteredPeerFeed event.Feed // Event feed for peer metrics
meteredPeerCount int32 // Actually stored peer connection count meteredPeerCount int32 // Actually stored peer connection count

View file

@ -29,7 +29,7 @@ import (
natpmp "github.com/jackpal/go-nat-pmp" natpmp "github.com/jackpal/go-nat-pmp"
) )
// An implementation of nat.Interface can map local ports to ports // Interface is an implementation of nat.Interface can map local ports to ports
// accessible from the Internet. // accessible from the Internet.
type Interface interface { type Interface interface {
// These methods manage a mapping between a port on the local // These methods manage a mapping between a port on the local
@ -131,13 +131,17 @@ func Map(m Interface, c chan struct{}, protocol string, extport, intport int, na
// Mapping operations will not return an error but won't actually do anything. // Mapping operations will not return an error but won't actually do anything.
type ExtIP net.IP type ExtIP net.IP
// ExternalIP returns the external ip address
func (n ExtIP) ExternalIP() (net.IP, error) { return net.IP(n), nil } func (n ExtIP) ExternalIP() (net.IP, error) { return net.IP(n), nil }
func (n ExtIP) String() string { return fmt.Sprintf("ExtIP(%v)", net.IP(n)) }
// These do nothing. // String returns a string representation of the external ip address
func (n ExtIP) String() string { return fmt.Sprintf("ExtIP(%v)", net.IP(n)) }
// AddMapping does nothing as it assumes the ports were mapped manually
func (ExtIP) AddMapping(string, int, int, string, time.Duration) error { return nil } func (ExtIP) AddMapping(string, int, int, string, time.Duration) error { return nil }
func (ExtIP) DeleteMapping(string, int, int) error { return nil }
// DeleteMapping does nothing as it assumes the ports were mapped manually
func (ExtIP) DeleteMapping(string, int, int) error { return nil }
// Any returns a port mapper that tries to discover any supported // Any returns a port mapper that tries to discover any supported
// mechanism on the local network. // mechanism on the local network.
@ -220,9 +224,8 @@ func (n *autodisc) String() string {
defer n.mu.Unlock() defer n.mu.Unlock()
if n.found == nil { if n.found == nil {
return n.what return n.what
} else {
return n.found.String()
} }
return n.found.String()
} }
// wait blocks until auto-discovery has been performed. // wait blocks until auto-discovery has been performed.

View file

@ -35,6 +35,8 @@ import (
) )
var ( var (
// ErrShuttingDown is the shutting down error
// which is used when the channel is closed
ErrShuttingDown = errors.New("shutting down") ErrShuttingDown = errors.New("shutting down")
) )
@ -193,6 +195,7 @@ func newPeer(log log.Logger, conn *conn, protocols []Protocol) *Peer {
return p return p
} }
// Log will return the logger
func (p *Peer) Log() log.Logger { func (p *Peer) Log() log.Logger {
return p.log return p.log
} }

View file

@ -54,21 +54,35 @@ func (pe *peerError) Error() string {
var errProtocolReturned = errors.New("protocol returned") var errProtocolReturned = errors.New("protocol returned")
// DiscReason is the code for a disconnect reason
type DiscReason uint type DiscReason uint
const ( const (
// DiscRequested is disconnect requested
DiscRequested DiscReason = iota DiscRequested DiscReason = iota
// DiscNetworkError is a network error
DiscNetworkError DiscNetworkError
// DiscProtocolError is a breach of protocol
DiscProtocolError DiscProtocolError
// DiscUselessPeer is a useless peer
DiscUselessPeer DiscUselessPeer
// DiscTooManyPeers is too many peers
DiscTooManyPeers DiscTooManyPeers
// DiscAlreadyConnected is already connected
DiscAlreadyConnected DiscAlreadyConnected
// DiscIncompatibleVersion is an incompatible p2p protocol version
DiscIncompatibleVersion DiscIncompatibleVersion
// DiscInvalidIdentity is invalid node entity
DiscInvalidIdentity DiscInvalidIdentity
// DiscQuitting is client quitting
DiscQuitting DiscQuitting
// DiscUnexpectedIdentity is an unexpected identity
DiscUnexpectedIdentity DiscUnexpectedIdentity
// DiscSelf is connected to self
DiscSelf DiscSelf
// DiscReadTimeout is read timeout
DiscReadTimeout DiscReadTimeout
// DiscSubprotocolError is subprotocol error
DiscSubprotocolError = 0x10 DiscSubprotocolError = 0x10
) )

View file

@ -363,7 +363,7 @@ func (srv *Server) RemoveTrustedPeer(node *enode.Node) {
} }
} }
// SubscribePeers subscribes the given channel to peer events // SubscribeEvents subscribes to peer events and returns the event subscription
func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription { func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription {
return srv.peerFeed.Subscribe(ch) return srv.peerFeed.Subscribe(ch)
} }

View file

@ -420,11 +420,11 @@ func startExecNodeStack() (*node.Node, error) {
} }
// create enode record // create enode record
nodeTcpConn, _ := net.ResolveTCPAddr("tcp", conf.Stack.P2P.ListenAddr) nodeTCPConn, _ := net.ResolveTCPAddr("tcp", conf.Stack.P2P.ListenAddr)
if nodeTcpConn.IP == nil { if nodeTCPConn.IP == nil {
nodeTcpConn.IP = net.IPv4(127, 0, 0, 1) nodeTCPConn.IP = net.IPv4(127, 0, 0, 1)
} }
conf.Node.initEnode(nodeTcpConn.IP, nodeTcpConn.Port, nodeTcpConn.Port) conf.Node.initEnode(nodeTCPConn.IP, nodeTCPConn.Port, nodeTCPConn.Port)
conf.Stack.P2P.PrivateKey = conf.Node.PrivateKey conf.Stack.P2P.PrivateKey = conf.Node.PrivateKey
conf.Stack.Logger = log.New("node.id", conf.Node.ID.String()) conf.Stack.Logger = log.New("node.id", conf.Node.ID.String())
@ -521,6 +521,7 @@ type SnapshotAPI struct {
services map[string]node.Service services map[string]node.Service
} }
// Snapshot will create snapshot of services
func (api SnapshotAPI) Snapshot() (map[string][]byte, error) { func (api SnapshotAPI) Snapshot() (map[string][]byte, error) {
snapshots := make(map[string][]byte) snapshots := make(map[string][]byte)
for name, service := range api.services { for name, service := range api.services {

View file

@ -201,11 +201,11 @@ func RandomNodeConfig() *NodeConfig {
panic("unable to assign tcp port") panic("unable to assign tcp port")
} }
enodId := enode.PubkeyToIDV4(&prvkey.PublicKey) enodID := enode.PubkeyToIDV4(&prvkey.PublicKey)
return &NodeConfig{ return &NodeConfig{
PrivateKey: prvkey, PrivateKey: prvkey,
ID: enodId, ID: enodID,
Name: fmt.Sprintf("node_%s", enodId.String()), Name: fmt.Sprintf("node_%s", enodID.String()),
Port: port, Port: port,
EnableMsgEvents: true, EnableMsgEvents: true,
} }
@ -279,12 +279,12 @@ func RegisterServices(services Services) {
// adds the host part to the configuration's ENR, signs it // adds the host part to the configuration's ENR, signs it
// creates and the corresponding enode object to the configuration // creates and the corresponding enode object to the configuration
func (n *NodeConfig) initEnode(ip net.IP, tcpport int, udpport int) error { func (n *NodeConfig) initEnode(ip net.IP, tcpport int, udpport int) error {
enrIp := enr.IP(ip) enrIP := enr.IP(ip)
n.Record.Set(&enrIp) n.Record.Set(&enrIP)
enrTcpPort := enr.TCP(tcpport) enrTCPPort := enr.TCP(tcpport)
n.Record.Set(&enrTcpPort) n.Record.Set(&enrTCPPort)
enrUdpPort := enr.UDP(udpport) enrUDPPort := enr.UDP(udpport)
n.Record.Set(&enrUdpPort) n.Record.Set(&enrUDPPort)
err := enode.SignV4(&n.Record, n.PrivateKey) err := enode.SignV4(&n.Record, n.PrivateKey)
if err != nil { if err != nil {

View file

@ -24,6 +24,7 @@ import (
) )
var ( var (
// ErrNodeNotFound is the node not found error
ErrNodeNotFound = errors.New("node not found") ErrNodeNotFound = errors.New("node not found")
) )

View file

@ -364,7 +364,7 @@ func (s *Server) StopMocker(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
} }
// GetMockerList returns a list of available mockers // GetMockers returns a list of available mockers
func (s *Server) GetMockers(w http.ResponseWriter, req *http.Request) { func (s *Server) GetMockers(w http.ResponseWriter, req *http.Request) {
list := GetMockerList() list := GetMockerList()

View file

@ -400,11 +400,11 @@ func startTestNetwork(t *testing.T, client *Client) []string {
// connect the nodes // connect the nodes
for i := 0; i < nodeCount-1; i++ { for i := 0; i < nodeCount-1; i++ {
peerId := i + 1 peerID := i + 1
if i == nodeCount-1 { if i == nodeCount-1 {
peerId = 0 peerID = 0
} }
if err := client.ConnectNode(nodeIDs[i], nodeIDs[peerId]); err != nil { if err := client.ConnectNode(nodeIDs[i], nodeIDs[peerID]); err != nil {
t.Fatalf("error connecting nodes: %s", err) t.Fatalf("error connecting nodes: %s", err)
} }
} }

View file

@ -36,13 +36,13 @@ var mockerList = map[string]func(net *Network, quit chan struct{}, nodeCount int
"boot": boot, "boot": boot,
} }
//Lookup a mocker by its name, returns the mockerFn // LookupMocker looks up a mocker by its name, returns the mocker function
func LookupMocker(mockerType string) func(net *Network, quit chan struct{}, nodeCount int) { func LookupMocker(mockerType string) func(net *Network, quit chan struct{}, nodeCount int) {
return mockerList[mockerType] return mockerList[mockerType]
} }
//Get a list of mockers (keys of the map) // GetMockerList will get a list of mockers (keys of the map)
//Useful for frontend to build available mocker selection // Useful for frontend to build available mocker selection
func GetMockerList() []string { func GetMockerList() []string {
list := make([]string, 0, len(mockerList)) list := make([]string, 0, len(mockerList))
for k := range mockerList { for k := range mockerList {

View file

@ -101,7 +101,7 @@ func TestMocker(t *testing.T) {
nodesComplete = true nodesComplete = true
} }
} else if event.Conn != nil && nodesComplete { } else if event.Conn != nil && nodesComplete {
connCount += 1 connCount++
} }
case <-time.After(30 * time.Second): case <-time.After(30 * time.Second):
t.Errorf("Timeout waiting for nodes being started up!") t.Errorf("Timeout waiting for nodes being started up!")

View file

@ -34,6 +34,7 @@ import (
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
) )
// DialBanTimeout is the time out for the network connections
var DialBanTimeout = 200 * time.Millisecond var DialBanTimeout = 200 * time.Millisecond
// NetworkConfig defines configuration options for starting a Network // NetworkConfig defines configuration options for starting a Network
@ -454,9 +455,8 @@ func (net *Network) getNodeIDs(excludeIDs []enode.ID) []enode.ID {
if len(excludeIDs) > 0 { if len(excludeIDs) > 0 {
// Return the difference of nodeIDs and excludeIDs // Return the difference of nodeIDs and excludeIDs
return filterIDs(nodeIDs, excludeIDs) return filterIDs(nodeIDs, excludeIDs)
} else {
return nodeIDs
} }
return nodeIDs
} }
// GetNodes returns the existing nodes. // GetNodes returns the existing nodes.
@ -472,9 +472,8 @@ func (net *Network) getNodes(excludeIDs []enode.ID) []*Node {
if len(excludeIDs) > 0 { if len(excludeIDs) > 0 {
nodeIDs := net.getNodeIDs(excludeIDs) nodeIDs := net.getNodeIDs(excludeIDs)
return net.getNodesByID(nodeIDs) return net.getNodesByID(nodeIDs)
} else {
return net.Nodes
} }
return net.Nodes
} }
// GetNodesByID returns existing nodes with the given enode.IDs. // GetNodesByID returns existing nodes with the given enode.IDs.
@ -651,7 +650,7 @@ func (net *Network) getConn(oneID, otherID enode.ID) *Conn {
return net.Conns[i] return net.Conns[i]
} }
// InitConn(one, other) retrieves the connection model for the connection between // InitConn (one, other) retrieves the connection model for the connection between
// peers one and other, or creates a new one if it does not exist // peers one and other, or creates a new one if it does not exist
// the order of nodes does not matter, i.e., Conn(i,j) == Conn(j, i) // the order of nodes does not matter, i.e., Conn(i,j) == Conn(j, i)
// it checks if the connection is already up, and if the nodes are running // it checks if the connection is already up, and if the nodes are running
@ -891,6 +890,7 @@ func (net *Network) Snapshot() (*Snapshot, error) {
return net.snapshot(nil, nil) return net.snapshot(nil, nil)
} }
// SnapshotWithServices will take a snapshot with the services specified as parameters
func (net *Network) SnapshotWithServices(addServices []string, removeServices []string) (*Snapshot, error) { func (net *Network) SnapshotWithServices(addServices []string, removeServices []string) (*Snapshot, error) {
return net.snapshot(addServices, removeServices) return net.snapshot(addServices, removeServices)
} }
@ -1098,7 +1098,6 @@ func (net *Network) executeNodeEvent(e *Event) error {
func (net *Network) executeConnEvent(e *Event) error { func (net *Network) executeConnEvent(e *Event) error {
if e.Conn.Up { if e.Conn.Up {
return net.Connect(e.Conn.One, e.Conn.Other) return net.Connect(e.Conn.One, e.Conn.Other)
} else {
return net.Disconnect(e.Conn.One, e.Conn.Other)
} }
return net.Disconnect(e.Conn.One, e.Conn.Other)
} }

View file

@ -113,6 +113,7 @@ func (s *Simulation) watchNetwork(result *StepResult) func() {
} }
} }
// Step is a struct for the action, trigger, and expectation
type Step struct { type Step struct {
// Action is the action to perform for this step // Action is the action to perform for this step
Action func(context.Context) error Action func(context.Context) error
@ -125,6 +126,7 @@ type Step struct {
Expect *Expectation Expect *Expectation
} }
// Expectation is a struct to hold the map of nodes and check function
type Expectation struct { type Expectation struct {
// Nodes is a list of nodes to check // Nodes is a list of nodes to check
Nodes []enode.ID Nodes []enode.ID
@ -139,6 +141,7 @@ func newStepResult() *StepResult {
} }
} }
// StepResult is a struct to hold the results from each step
type StepResult struct { type StepResult struct {
// Error is the error encountered whilst running the step // Error is the error encountered whilst running the step
Error error Error error

View file

@ -31,12 +31,14 @@ type NoopService struct {
c map[enode.ID]chan struct{} c map[enode.ID]chan struct{}
} }
// NewNoopService will return a NoopService
func NewNoopService(ackC map[enode.ID]chan struct{}) *NoopService { func NewNoopService(ackC map[enode.ID]chan struct{}) *NoopService {
return &NoopService{ return &NoopService{
c: ackC, c: ackC,
} }
} }
// Protocols will return the protocols
func (t *NoopService) Protocols() []p2p.Protocol { func (t *NoopService) Protocols() []p2p.Protocol {
return []p2p.Protocol{ return []p2p.Protocol{
{ {
@ -62,18 +64,23 @@ func (t *NoopService) Protocols() []p2p.Protocol {
} }
} }
// APIs will return an empty map of rpc APIs
func (t *NoopService) APIs() []rpc.API { func (t *NoopService) APIs() []rpc.API {
return []rpc.API{} return []rpc.API{}
} }
// Start is not implemented
func (t *NoopService) Start(server *p2p.Server) error { func (t *NoopService) Start(server *p2p.Server) error {
return nil return nil
} }
// Stop is not implemented
func (t *NoopService) Stop() error { func (t *NoopService) Stop() error {
return nil return nil
} }
// VerifyRing will verify the ring network by going thru all of the
// network ids and verify connection status
func VerifyRing(t *testing.T, net *Network, ids []enode.ID) { func VerifyRing(t *testing.T, net *Network, ids []enode.ID) {
t.Helper() t.Helper()
n := len(ids) n := len(ids)
@ -93,6 +100,8 @@ func VerifyRing(t *testing.T, net *Network, ids []enode.ID) {
} }
} }
// VerifyChain will verify the chain by going thru all of the
// network ids and verify connection status
func VerifyChain(t *testing.T, net *Network, ids []enode.ID) { func VerifyChain(t *testing.T, net *Network, ids []enode.ID) {
t.Helper() t.Helper()
n := len(ids) n := len(ids)
@ -112,6 +121,8 @@ func VerifyChain(t *testing.T, net *Network, ids []enode.ID) {
} }
} }
// VerifyFull will verify connections by going thru all network ids
// and verifying if we have the valid number of connections
func VerifyFull(t *testing.T, net *Network, ids []enode.ID) { func VerifyFull(t *testing.T, net *Network, ids []enode.ID) {
t.Helper() t.Helper()
n := len(ids) n := len(ids)
@ -130,6 +141,8 @@ func VerifyFull(t *testing.T, net *Network, ids []enode.ID) {
} }
} }
// VerifyStar will verify the star network by going thru all of the
// the network ids and validating connection status
func VerifyStar(t *testing.T, net *Network, ids []enode.ID, centerIndex int) { func VerifyStar(t *testing.T, net *Network, ids []enode.ID, centerIndex int) {
t.Helper() t.Helper()
n := len(ids) n := len(ids)

View file

@ -24,6 +24,7 @@ import (
"github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enode"
) )
// TestPeer holds a test peer entry
type TestPeer interface { type TestPeer interface {
ID() enode.ID ID() enode.ID
Drop() Drop()
@ -35,10 +36,12 @@ type TestPeerPool struct {
peers map[enode.ID]TestPeer peers map[enode.ID]TestPeer
} }
// NewTestPeerPool will create a new peer pool for testing
func NewTestPeerPool() *TestPeerPool { func NewTestPeerPool() *TestPeerPool {
return &TestPeerPool{peers: make(map[enode.ID]TestPeer)} return &TestPeerPool{peers: make(map[enode.ID]TestPeer)}
} }
// Add adds a peer to the test peer pool
func (p *TestPeerPool) Add(peer TestPeer) { func (p *TestPeerPool) Add(peer TestPeer) {
p.lock.Lock() p.lock.Lock()
defer p.lock.Unlock() defer p.lock.Unlock()
@ -47,12 +50,14 @@ func (p *TestPeerPool) Add(peer TestPeer) {
} }
// Remove removes a peer from the test peer pool
func (p *TestPeerPool) Remove(peer TestPeer) { func (p *TestPeerPool) Remove(peer TestPeer) {
p.lock.Lock() p.lock.Lock()
defer p.lock.Unlock() defer p.lock.Unlock()
delete(p.peers, peer.ID()) delete(p.peers, peer.ID())
} }
// Has returns true if the peer is in the test peer pool
func (p *TestPeerPool) Has(id enode.ID) bool { func (p *TestPeerPool) Has(id enode.ID) bool {
p.lock.Lock() p.lock.Lock()
defer p.lock.Unlock() defer p.lock.Unlock()
@ -60,6 +65,7 @@ func (p *TestPeerPool) Has(id enode.ID) bool {
return ok return ok
} }
// Get returns the peer from the test peer pool
func (p *TestPeerPool) Get(id enode.ID) TestPeer { func (p *TestPeerPool) Get(id enode.ID) TestPeer {
p.lock.Lock() p.lock.Lock()
defer p.lock.Unlock() defer p.lock.Unlock()