2015-07-07 00:54:22 +00:00
|
|
|
// Copyright 2015 The go-ethereum Authors
|
2015-07-22 16:48:40 +00:00
|
|
|
// This file is part of the go-ethereum library.
|
2015-07-07 00:54:22 +00:00
|
|
|
//
|
2015-07-23 16:35:11 +00:00
|
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
2015-07-07 00:54:22 +00:00
|
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
2015-07-22 16:48:40 +00:00
|
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
2015-07-07 00:54:22 +00:00
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
2015-07-22 16:48:40 +00:00
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
2015-07-07 00:54:22 +00:00
|
|
|
// GNU Lesser General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Lesser General Public License
|
2015-07-22 16:48:40 +00:00
|
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
2015-07-07 00:54:22 +00:00
|
|
|
|
2015-05-15 22:38:28 +00:00
|
|
|
package p2p
|
|
|
|
|
|
|
|
import (
|
2020-02-13 10:10:03 +00:00
|
|
|
"context"
|
|
|
|
crand "crypto/rand"
|
|
|
|
"encoding/binary"
|
2016-11-22 19:51:59 +00:00
|
|
|
"errors"
|
2015-05-15 22:38:28 +00:00
|
|
|
"fmt"
|
2020-02-13 10:10:03 +00:00
|
|
|
mrand "math/rand"
|
2015-05-15 22:38:28 +00:00
|
|
|
"net"
|
2020-02-13 10:10:03 +00:00
|
|
|
"sync"
|
2020-10-20 21:23:56 +00:00
|
|
|
"sync/atomic"
|
2015-05-15 22:38:28 +00:00
|
|
|
"time"
|
|
|
|
|
2021-06-13 16:41:39 +00:00
|
|
|
"github.com/ledgerwatch/erigon/common/debug"
|
2021-05-20 18:25:53 +00:00
|
|
|
"github.com/ledgerwatch/erigon/common/mclock"
|
|
|
|
"github.com/ledgerwatch/erigon/p2p/enode"
|
|
|
|
"github.com/ledgerwatch/erigon/p2p/netutil"
|
2021-07-29 10:23:23 +00:00
|
|
|
"github.com/ledgerwatch/log/v3"
|
2015-05-15 22:38:28 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2019-06-11 10:45:33 +00:00
|
|
|
// This is the amount of time spent waiting in between redialing a certain node. The
|
|
|
|
// limit is a bit higher than inboundThrottleTime to prevent failing dials in small
|
|
|
|
// private networks.
|
|
|
|
dialHistoryExpiration = inboundThrottleTime + 5*time.Second
|
2015-05-15 22:38:28 +00:00
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// Config for the "Looking for peers" message.
|
2021-07-04 03:55:34 +00:00
|
|
|
dialStatsLogInterval = 60 * time.Second // printed at most this often
|
2017-04-10 16:33:41 +00:00
|
|
|
|
2015-10-22 21:46:28 +00:00
|
|
|
// Endpoint resolution is throttled with bounded backoff.
|
|
|
|
initialResolveDelay = 60 * time.Second
|
|
|
|
maxResolveDelay = time.Hour
|
2015-05-15 22:38:28 +00:00
|
|
|
)
|
|
|
|
|
2017-09-25 08:08:07 +00:00
|
|
|
// NodeDialer is used to connect to nodes in the network, typically by using
|
2020-02-13 10:10:03 +00:00
|
|
|
// an underlying net.Dialer but also using net.Pipe in tests.
|
2017-09-25 08:08:07 +00:00
|
|
|
type NodeDialer interface {
|
2020-02-13 10:10:03 +00:00
|
|
|
Dial(context.Context, *enode.Node) (net.Conn, error)
|
2017-09-25 08:08:07 +00:00
|
|
|
}
|
|
|
|
|
2019-10-29 15:08:57 +00:00
|
|
|
type nodeResolver interface {
|
|
|
|
Resolve(*enode.Node) *enode.Node
|
|
|
|
}
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// tcpDialer implements NodeDialer using real TCP connections.
|
|
|
|
type tcpDialer struct {
|
|
|
|
d *net.Dialer
|
2017-09-25 08:08:07 +00:00
|
|
|
}
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
func (t tcpDialer) Dial(ctx context.Context, dest *enode.Node) (net.Conn, error) {
|
|
|
|
return t.d.DialContext(ctx, "tcp", nodeAddr(dest).String())
|
2017-09-25 08:08:07 +00:00
|
|
|
}
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
func nodeAddr(n *enode.Node) net.Addr {
|
|
|
|
return &net.TCPAddr{IP: n.IP(), Port: n.TCP()}
|
|
|
|
}
|
|
|
|
|
|
|
|
// checkDial errors:
|
|
|
|
var (
|
|
|
|
errSelf = errors.New("is self")
|
|
|
|
errAlreadyDialing = errors.New("already dialing")
|
|
|
|
errAlreadyConnected = errors.New("already connected")
|
|
|
|
errRecentlyDialed = errors.New("recently dialed")
|
|
|
|
errNotWhitelisted = errors.New("not contained in netrestrict whitelist")
|
2020-05-11 15:11:17 +00:00
|
|
|
errNoPort = errors.New("node does not provide TCP port")
|
2020-02-13 10:10:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// dialer creates outbound connections and submits them into Server.
|
|
|
|
// Two types of peer connections can be created:
|
|
|
|
//
|
2022-08-10 12:04:13 +00:00
|
|
|
// - static dials are pre-configured connections. The dialer attempts
|
|
|
|
// keep these nodes connected at all times.
|
2020-02-13 10:10:03 +00:00
|
|
|
//
|
2022-08-10 12:04:13 +00:00
|
|
|
// - dynamic dials are created from node discovery results. The dialer
|
|
|
|
// continuously reads candidate nodes from its input iterator and attempts
|
|
|
|
// to create peer connections to nodes arriving through the iterator.
|
2020-02-13 10:10:03 +00:00
|
|
|
type dialScheduler struct {
|
|
|
|
dialConfig
|
2023-11-07 08:48:58 +00:00
|
|
|
mutex sync.Mutex
|
2020-02-13 10:10:03 +00:00
|
|
|
setupFunc dialSetupFunc
|
|
|
|
wg sync.WaitGroup
|
|
|
|
cancel context.CancelFunc
|
|
|
|
ctx context.Context
|
|
|
|
nodesIn chan *enode.Node
|
|
|
|
doneCh chan *dialTask
|
|
|
|
addStaticCh chan *enode.Node
|
|
|
|
remStaticCh chan *enode.Node
|
|
|
|
addPeerCh chan *conn
|
|
|
|
remPeerCh chan *conn
|
|
|
|
|
2021-07-03 03:35:11 +00:00
|
|
|
subProtocolVersion uint
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// Everything below here belongs to loop and
|
|
|
|
// should only be accessed by code on the loop goroutine.
|
|
|
|
dialing map[enode.ID]*dialTask // active tasks
|
|
|
|
peers map[enode.ID]connFlag // all connected peers
|
|
|
|
dialPeers int // current number of dialed peers
|
|
|
|
|
|
|
|
// The static map tracks all static dial tasks. The subset of usable static dial tasks
|
|
|
|
// (i.e. those passing checkDial) is kept in staticPool. The scheduler prefers
|
|
|
|
// launching random static tasks from the pool over launching dynamic dials from the
|
|
|
|
// iterator.
|
|
|
|
static map[enode.ID]*dialTask
|
|
|
|
staticPool []*dialTask
|
|
|
|
|
|
|
|
// The dial history keeps recently dialed nodes. Members of history are not dialed.
|
|
|
|
history expHeap
|
|
|
|
historyTimer mclock.Timer
|
|
|
|
historyTimerTime mclock.AbsTime
|
|
|
|
|
|
|
|
// for logStats
|
2023-11-07 08:48:58 +00:00
|
|
|
dialed int
|
|
|
|
errors map[string]uint
|
2020-02-13 10:10:03 +00:00
|
|
|
}
|
2015-05-15 22:38:28 +00:00
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
type dialSetupFunc func(net.Conn, connFlag, *enode.Node) error
|
|
|
|
|
|
|
|
type dialConfig struct {
|
|
|
|
self enode.ID // our own ID
|
|
|
|
maxDialPeers int // maximum number of dialed peers
|
|
|
|
maxActiveDials int // maximum number of active dials
|
|
|
|
netRestrict *netutil.Netlist // IP whitelist, disabled if nil
|
|
|
|
resolver nodeResolver
|
|
|
|
dialer NodeDialer
|
|
|
|
log log.Logger
|
|
|
|
clock mclock.Clock
|
|
|
|
rand *mrand.Rand
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
func (cfg dialConfig) withDefaults() dialConfig {
|
|
|
|
if cfg.log == nil {
|
|
|
|
cfg.log = log.Root()
|
|
|
|
}
|
|
|
|
if cfg.clock == nil {
|
|
|
|
cfg.clock = mclock.System{}
|
|
|
|
}
|
|
|
|
if cfg.rand == nil {
|
|
|
|
seedb := make([]byte, 8)
|
2020-02-21 15:25:11 +00:00
|
|
|
if _, err := crand.Read(seedb); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
seed := int64(binary.BigEndian.Uint64(seedb))
|
2022-08-17 05:18:19 +00:00
|
|
|
cfg.rand = mrand.New(mrand.NewSource(seed)) // nolint: gosec
|
2020-02-13 10:10:03 +00:00
|
|
|
}
|
|
|
|
return cfg
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
|
|
|
|
2021-07-03 03:35:11 +00:00
|
|
|
func newDialScheduler(config dialConfig, it enode.Iterator, setupFunc dialSetupFunc, subProtocolVersion uint) *dialScheduler {
|
2020-02-13 10:10:03 +00:00
|
|
|
d := &dialScheduler{
|
|
|
|
dialConfig: config.withDefaults(),
|
|
|
|
setupFunc: setupFunc,
|
|
|
|
dialing: make(map[enode.ID]*dialTask),
|
all: new p2p node representation (#17643)
Package p2p/enode provides a generalized representation of p2p nodes
which can contain arbitrary information in key/value pairs. It is also
the new home for the node database. The "v4" identity scheme is also
moved here from p2p/enr to remove the dependency on Ethereum crypto from
that package.
Record signature handling is changed significantly. The identity scheme
registry is removed and acceptable schemes must be passed to any method
that needs identity. This means records must now be validated explicitly
after decoding.
The enode API is designed to make signature handling easy and safe: most
APIs around the codebase work with enode.Node, which is a wrapper around
a valid record. Going from enr.Record to enode.Node requires a valid
signature.
* p2p/discover: port to p2p/enode
This ports the discovery code to the new node representation in
p2p/enode. The wire protocol is unchanged, this can be considered a
refactoring change. The Kademlia table can now deal with nodes using an
arbitrary identity scheme. This requires a few incompatible API changes:
- Table.Lookup is not available anymore. It used to take a public key
as argument because v4 protocol requires one. Its replacement is
LookupRandom.
- Table.Resolve takes *enode.Node instead of NodeID. This is also for
v4 protocol compatibility because nodes cannot be looked up by ID
alone.
- Types Node and NodeID are gone. Further commits in the series will be
fixes all over the the codebase to deal with those removals.
* p2p: port to p2p/enode and discovery changes
This adapts package p2p to the changes in p2p/discover. All uses of
discover.Node and discover.NodeID are replaced by their equivalents from
p2p/enode.
New API is added to retrieve the enode.Node instance of a peer. The
behavior of Server.Self with discovery disabled is improved. It now
tries much harder to report a working IP address, falling back to
127.0.0.1 if no suitable address can be determined through other means.
These changes were needed for tests of other packages later in the
series.
* p2p/simulations, p2p/testing: port to p2p/enode
No surprises here, mostly replacements of discover.Node, discover.NodeID
with their new equivalents. The 'interesting' API changes are:
- testing.ProtocolSession tracks complete nodes, not just their IDs.
- adapters.NodeConfig has a new method to create a complete node.
These changes were needed to make swarm tests work.
Note that the NodeID change makes the code incompatible with old
simulation snapshots.
* whisper/whisperv5, whisper/whisperv6: port to p2p/enode
This port was easy because whisper uses []byte for node IDs and
URL strings in the API.
* eth: port to p2p/enode
Again, easy to port because eth uses strings for node IDs and doesn't
care about node information in any way.
* les: port to p2p/enode
Apart from replacing discover.NodeID with enode.ID, most changes are in
the server pool code. It now deals with complete nodes instead
of (Pubkey, IP, Port) triples. The database format is unchanged for now,
but we should probably change it to use the node database later.
* node: port to p2p/enode
This change simply replaces discover.Node and discover.NodeID with their
new equivalents.
* swarm/network: port to p2p/enode
Swarm has its own node address representation, BzzAddr, containing both
an overlay address (the hash of a secp256k1 public key) and an underlay
address (enode:// URL).
There are no changes to the BzzAddr format in this commit, but certain
operations such as creating a BzzAddr from a node ID are now impossible
because node IDs aren't public keys anymore.
Most swarm-related changes in the series remove uses of
NewAddrFromNodeID, replacing it with NewAddr which takes a complete node
as argument. ToOverlayAddr is removed because we can just use the node
ID directly.
2018-09-24 22:59:00 +00:00
|
|
|
static: make(map[enode.ID]*dialTask),
|
2020-02-13 10:10:03 +00:00
|
|
|
peers: make(map[enode.ID]connFlag),
|
|
|
|
doneCh: make(chan *dialTask),
|
|
|
|
nodesIn: make(chan *enode.Node),
|
|
|
|
addStaticCh: make(chan *enode.Node),
|
|
|
|
remStaticCh: make(chan *enode.Node),
|
|
|
|
addPeerCh: make(chan *conn),
|
|
|
|
remPeerCh: make(chan *conn),
|
2021-07-03 03:35:11 +00:00
|
|
|
|
|
|
|
subProtocolVersion: subProtocolVersion,
|
2023-11-07 08:48:58 +00:00
|
|
|
errors: map[string]uint{},
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
2023-11-07 08:48:58 +00:00
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
d.ctx, d.cancel = context.WithCancel(context.Background())
|
|
|
|
d.wg.Add(2)
|
|
|
|
go d.readNodes(it)
|
|
|
|
go d.loop(it)
|
|
|
|
return d
|
|
|
|
}
|
|
|
|
|
|
|
|
// stop shuts down the dialer, canceling all current dial tasks.
|
|
|
|
func (d *dialScheduler) stop() {
|
|
|
|
d.cancel()
|
|
|
|
d.wg.Wait()
|
|
|
|
}
|
|
|
|
|
|
|
|
// addStatic adds a static dial candidate.
|
|
|
|
func (d *dialScheduler) addStatic(n *enode.Node) {
|
|
|
|
select {
|
|
|
|
case d.addStaticCh <- n:
|
|
|
|
case <-d.ctx.Done():
|
2019-06-11 10:45:33 +00:00
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// removeStatic removes a static dial candidate.
|
|
|
|
func (d *dialScheduler) removeStatic(n *enode.Node) {
|
|
|
|
select {
|
|
|
|
case d.remStaticCh <- n:
|
|
|
|
case <-d.ctx.Done():
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// peerAdded updates the peer set.
|
|
|
|
func (d *dialScheduler) peerAdded(c *conn) {
|
|
|
|
select {
|
|
|
|
case d.addPeerCh <- c:
|
|
|
|
case <-d.ctx.Done():
|
|
|
|
}
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// peerRemoved updates the peer set.
|
|
|
|
func (d *dialScheduler) peerRemoved(c *conn) {
|
|
|
|
select {
|
|
|
|
case d.remPeerCh <- c:
|
|
|
|
case <-d.ctx.Done():
|
|
|
|
}
|
2016-06-24 20:27:55 +00:00
|
|
|
}
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// loop is the main loop of the dialer.
|
|
|
|
func (d *dialScheduler) loop(it enode.Iterator) {
|
2021-06-22 10:09:45 +00:00
|
|
|
defer debug.LogPanic()
|
2020-02-13 10:10:03 +00:00
|
|
|
var (
|
|
|
|
nodesCh chan *enode.Node
|
|
|
|
historyExp = make(chan struct{}, 1)
|
|
|
|
)
|
|
|
|
|
2023-11-07 08:48:58 +00:00
|
|
|
logTimer := time.NewTicker(dialStatsLogInterval)
|
|
|
|
defer logTimer.Stop()
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
loop:
|
|
|
|
for {
|
|
|
|
// Launch new dials if slots are available.
|
|
|
|
slots := d.freeDialSlots()
|
2021-10-07 01:33:13 +00:00
|
|
|
d.startStaticDials()
|
2020-02-13 10:10:03 +00:00
|
|
|
if slots > 0 {
|
|
|
|
nodesCh = d.nodesIn
|
|
|
|
} else {
|
|
|
|
nodesCh = nil
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
d.rearmHistoryTimer(historyExp)
|
|
|
|
|
|
|
|
select {
|
2020-11-02 21:07:26 +00:00
|
|
|
case <-d.ctx.Done():
|
|
|
|
it.Close()
|
|
|
|
break loop
|
|
|
|
|
2023-11-07 08:48:58 +00:00
|
|
|
case <-logTimer.C:
|
|
|
|
d.logStats()
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
case node := <-nodesCh:
|
|
|
|
if err := d.checkDial(node); err != nil {
|
|
|
|
d.log.Trace("Discarding dial candidate", "id", node.ID(), "ip", node.IP(), "reason", err)
|
|
|
|
} else {
|
|
|
|
d.startDial(newDialTask(node, dynDialedConn))
|
|
|
|
}
|
|
|
|
|
|
|
|
case task := <-d.doneCh:
|
|
|
|
id := task.dest.ID()
|
|
|
|
delete(d.dialing, id)
|
|
|
|
d.updateStaticPool(id)
|
2023-11-07 08:48:58 +00:00
|
|
|
d.dialed++
|
2020-02-13 10:10:03 +00:00
|
|
|
|
|
|
|
case c := <-d.addPeerCh:
|
|
|
|
if c.is(dynDialedConn) || c.is(staticDialedConn) {
|
|
|
|
d.dialPeers++
|
|
|
|
}
|
|
|
|
id := c.node.ID()
|
2020-10-20 21:23:56 +00:00
|
|
|
d.peers[id] = connFlag(atomic.LoadInt32((*int32)(&c.flags)))
|
2020-02-13 10:10:03 +00:00
|
|
|
// Remove from static pool because the node is now connected.
|
|
|
|
task := d.static[id]
|
|
|
|
if task != nil && task.staticPoolIndex >= 0 {
|
|
|
|
d.removeFromStaticPool(task.staticPoolIndex)
|
|
|
|
}
|
|
|
|
// TODO: cancel dials to connected peers
|
|
|
|
|
|
|
|
case c := <-d.remPeerCh:
|
|
|
|
if c.is(dynDialedConn) || c.is(staticDialedConn) {
|
|
|
|
d.dialPeers--
|
|
|
|
}
|
|
|
|
delete(d.peers, c.node.ID())
|
|
|
|
d.updateStaticPool(c.node.ID())
|
|
|
|
|
|
|
|
case node := <-d.addStaticCh:
|
|
|
|
id := node.ID()
|
|
|
|
_, exists := d.static[id]
|
|
|
|
d.log.Trace("Adding static node", "id", id, "ip", node.IP(), "added", !exists)
|
|
|
|
if exists {
|
|
|
|
continue loop
|
|
|
|
}
|
|
|
|
task := newDialTask(node, staticDialedConn)
|
|
|
|
d.static[id] = task
|
|
|
|
if d.checkDial(node) == nil {
|
|
|
|
d.addToStaticPool(task)
|
|
|
|
}
|
|
|
|
|
|
|
|
case node := <-d.remStaticCh:
|
|
|
|
id := node.ID()
|
|
|
|
task := d.static[id]
|
|
|
|
d.log.Trace("Removing static node", "id", id, "ok", task != nil)
|
|
|
|
if task != nil {
|
|
|
|
delete(d.static, id)
|
|
|
|
if task.staticPoolIndex >= 0 {
|
|
|
|
d.removeFromStaticPool(task.staticPoolIndex)
|
|
|
|
}
|
|
|
|
}
|
2019-10-29 15:08:57 +00:00
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
case <-historyExp:
|
|
|
|
d.expireHistory()
|
|
|
|
|
2019-10-29 15:08:57 +00:00
|
|
|
}
|
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
|
|
|
|
d.stopHistoryTimer(historyExp)
|
|
|
|
for range d.dialing {
|
|
|
|
<-d.doneCh
|
2019-10-29 15:08:57 +00:00
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
d.wg.Done()
|
|
|
|
}
|
|
|
|
|
|
|
|
// readNodes runs in its own goroutine and delivers nodes from
|
|
|
|
// the input iterator to the nodesIn channel.
|
|
|
|
func (d *dialScheduler) readNodes(it enode.Iterator) {
|
2021-06-22 10:09:45 +00:00
|
|
|
defer debug.LogPanic()
|
2020-02-13 10:10:03 +00:00
|
|
|
defer d.wg.Done()
|
2019-10-29 15:08:57 +00:00
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
for it.Next() {
|
|
|
|
select {
|
|
|
|
case d.nodesIn <- it.Node():
|
|
|
|
case <-d.ctx.Done():
|
2017-04-10 16:33:41 +00:00
|
|
|
}
|
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
}
|
2019-10-29 15:08:57 +00:00
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// or comes back online.
|
2022-08-10 12:04:13 +00:00
|
|
|
// nolint
|
2021-07-04 03:55:34 +00:00
|
|
|
func (d *dialScheduler) logStats() {
|
2023-11-07 08:48:58 +00:00
|
|
|
vals := []interface{}{"protocol", d.subProtocolVersion,
|
|
|
|
"peers", fmt.Sprintf("%d/%d", len(d.peers), d.maxDialPeers), "tried", d.dialed, "static", len(d.static)}
|
|
|
|
|
|
|
|
d.mutex.Lock()
|
|
|
|
for err, count := range d.errors {
|
|
|
|
vals = append(vals, err, count)
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
2023-11-07 08:48:58 +00:00
|
|
|
d.mutex.Unlock()
|
|
|
|
|
|
|
|
d.log.Debug("[p2p] Dial scheduler", vals...)
|
2020-02-13 10:10:03 +00:00
|
|
|
}
|
2019-10-29 15:08:57 +00:00
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// rearmHistoryTimer configures d.historyTimer to fire when the
|
|
|
|
// next item in d.history expires.
|
|
|
|
func (d *dialScheduler) rearmHistoryTimer(ch chan struct{}) {
|
|
|
|
if len(d.history) == 0 || d.historyTimerTime == d.history.nextExpiry() {
|
|
|
|
return
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
d.stopHistoryTimer(ch)
|
|
|
|
d.historyTimerTime = d.history.nextExpiry()
|
|
|
|
timeout := time.Duration(d.historyTimerTime - d.clock.Now())
|
|
|
|
d.historyTimer = d.clock.AfterFunc(timeout, func() { ch <- struct{}{} })
|
|
|
|
}
|
2015-05-15 22:38:28 +00:00
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// stopHistoryTimer stops the timer and drains the channel it sends on.
|
|
|
|
func (d *dialScheduler) stopHistoryTimer(ch chan struct{}) {
|
|
|
|
if d.historyTimer != nil && !d.historyTimer.Stop() {
|
|
|
|
<-ch
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// expireHistory removes expired items from d.history.
|
|
|
|
func (d *dialScheduler) expireHistory() {
|
|
|
|
d.historyTimer.Stop()
|
|
|
|
d.historyTimer = nil
|
|
|
|
d.historyTimerTime = 0
|
|
|
|
d.history.expire(d.clock.Now(), func(hkey string) {
|
|
|
|
var id enode.ID
|
|
|
|
copy(id[:], hkey)
|
|
|
|
d.updateStaticPool(id)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// freeDialSlots returns the number of free dial slots. The result can be negative
|
|
|
|
// when peers are connected while their task is still running.
|
|
|
|
func (d *dialScheduler) freeDialSlots() int {
|
|
|
|
slots := (d.maxDialPeers - d.dialPeers) * 2
|
|
|
|
if slots > d.maxActiveDials {
|
|
|
|
slots = d.maxActiveDials
|
|
|
|
}
|
|
|
|
free := slots - len(d.dialing)
|
|
|
|
return free
|
|
|
|
}
|
2016-11-22 19:51:59 +00:00
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// checkDial returns an error if node n should not be dialed.
|
|
|
|
func (d *dialScheduler) checkDial(n *enode.Node) error {
|
|
|
|
if n.ID() == d.self {
|
|
|
|
return errSelf
|
|
|
|
}
|
2020-05-11 15:11:17 +00:00
|
|
|
if n.IP() != nil && n.TCP() == 0 {
|
|
|
|
// This check can trigger if a non-TCP node is found
|
|
|
|
// by discovery. If there is no IP, the node is a static
|
|
|
|
// node and the actual endpoint will be resolved later in dialTask.
|
|
|
|
return errNoPort
|
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
if _, ok := d.dialing[n.ID()]; ok {
|
2016-11-22 19:51:59 +00:00
|
|
|
return errAlreadyDialing
|
2020-02-13 10:10:03 +00:00
|
|
|
}
|
|
|
|
if _, ok := d.peers[n.ID()]; ok {
|
2016-11-22 19:51:59 +00:00
|
|
|
return errAlreadyConnected
|
2020-02-13 10:10:03 +00:00
|
|
|
}
|
|
|
|
if d.netRestrict != nil && !d.netRestrict.Contains(n.IP()) {
|
2016-11-22 19:51:59 +00:00
|
|
|
return errNotWhitelisted
|
2020-02-13 10:10:03 +00:00
|
|
|
}
|
|
|
|
if d.history.contains(string(n.ID().Bytes())) {
|
2016-11-22 19:51:59 +00:00
|
|
|
return errRecentlyDialed
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// startStaticDials starts n static dial tasks.
|
2021-10-07 01:33:13 +00:00
|
|
|
func (d *dialScheduler) startStaticDials() {
|
|
|
|
for len(d.staticPool) > 0 {
|
2020-02-13 10:10:03 +00:00
|
|
|
idx := d.rand.Intn(len(d.staticPool))
|
|
|
|
task := d.staticPool[idx]
|
|
|
|
d.startDial(task)
|
|
|
|
d.removeFromStaticPool(idx)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// updateStaticPool attempts to move the given static dial back into staticPool.
|
|
|
|
func (d *dialScheduler) updateStaticPool(id enode.ID) {
|
|
|
|
task, ok := d.static[id]
|
|
|
|
if ok && task.staticPoolIndex < 0 && d.checkDial(task.dest) == nil {
|
|
|
|
d.addToStaticPool(task)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *dialScheduler) addToStaticPool(task *dialTask) {
|
|
|
|
if task.staticPoolIndex >= 0 {
|
|
|
|
panic("attempt to add task to staticPool twice")
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
d.staticPool = append(d.staticPool, task)
|
|
|
|
task.staticPoolIndex = len(d.staticPool) - 1
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
// removeFromStaticPool removes the task at idx from staticPool. It does that by moving the
|
|
|
|
// current last element of the pool to idx and then shortening the pool by one.
|
|
|
|
func (d *dialScheduler) removeFromStaticPool(idx int) {
|
|
|
|
task := d.staticPool[idx]
|
|
|
|
end := len(d.staticPool) - 1
|
|
|
|
d.staticPool[idx] = d.staticPool[end]
|
|
|
|
d.staticPool[idx].staticPoolIndex = idx
|
|
|
|
d.staticPool[end] = nil
|
|
|
|
d.staticPool = d.staticPool[:end]
|
|
|
|
task.staticPoolIndex = -1
|
|
|
|
}
|
|
|
|
|
|
|
|
// startDial runs the given dial task in a separate goroutine.
|
|
|
|
func (d *dialScheduler) startDial(task *dialTask) {
|
|
|
|
d.log.Trace("Starting p2p dial", "id", task.dest.ID(), "ip", task.dest.IP(), "flag", task.flags)
|
|
|
|
hkey := string(task.dest.ID().Bytes())
|
|
|
|
d.history.add(hkey, d.clock.Now().Add(dialHistoryExpiration))
|
|
|
|
d.dialing[task.dest.ID()] = task
|
|
|
|
go func() {
|
2021-06-22 10:09:45 +00:00
|
|
|
defer debug.LogPanic()
|
2020-02-13 10:10:03 +00:00
|
|
|
task.run(d)
|
|
|
|
d.doneCh <- task
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
// A dialTask generated for each node that is dialed.
|
2019-10-29 15:08:57 +00:00
|
|
|
type dialTask struct {
|
2020-02-13 10:10:03 +00:00
|
|
|
staticPoolIndex int
|
|
|
|
flags connFlag
|
|
|
|
// These fields are private to the task and should not be
|
|
|
|
// accessed by dialScheduler while the task is running.
|
2019-10-29 15:08:57 +00:00
|
|
|
dest *enode.Node
|
2020-02-13 10:10:03 +00:00
|
|
|
lastResolved mclock.AbsTime
|
2019-10-29 15:08:57 +00:00
|
|
|
resolveDelay time.Duration
|
|
|
|
}
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
func newDialTask(dest *enode.Node, flags connFlag) *dialTask {
|
|
|
|
return &dialTask{dest: dest, flags: flags, staticPoolIndex: -1}
|
|
|
|
}
|
|
|
|
|
|
|
|
type dialError struct {
|
|
|
|
error
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *dialTask) run(d *dialScheduler) {
|
2020-05-11 15:11:17 +00:00
|
|
|
if t.needResolve() && !t.resolve(d) {
|
|
|
|
return
|
2015-10-22 21:46:28 +00:00
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
|
|
|
|
err := t.dial(d, t.dest)
|
2017-12-01 11:49:04 +00:00
|
|
|
if err != nil {
|
2020-05-11 15:11:17 +00:00
|
|
|
// For static nodes, resolve one more time if dialing fails.
|
2017-12-01 11:49:04 +00:00
|
|
|
if _, ok := err.(*dialError); ok && t.flags&staticDialedConn != 0 {
|
2020-02-13 10:10:03 +00:00
|
|
|
if t.resolve(d) {
|
2020-02-21 15:25:11 +00:00
|
|
|
t.dial(d, t.dest) //nolint:errcheck
|
2017-12-01 11:49:04 +00:00
|
|
|
}
|
2015-10-22 21:46:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-11 15:11:17 +00:00
|
|
|
func (t *dialTask) needResolve() bool {
|
|
|
|
return t.flags&staticDialedConn != 0 && t.dest.IP() == nil
|
|
|
|
}
|
|
|
|
|
2015-10-22 21:46:28 +00:00
|
|
|
// resolve attempts to find the current endpoint for the destination
|
|
|
|
// using discovery.
|
|
|
|
//
|
|
|
|
// Resolve operations are throttled with backoff to avoid flooding the
|
|
|
|
// discovery network with useless queries for nodes that don't exist.
|
|
|
|
// The backoff delay resets when the node is found.
|
2020-02-13 10:10:03 +00:00
|
|
|
func (t *dialTask) resolve(d *dialScheduler) bool {
|
|
|
|
if d.resolver == nil {
|
2015-10-22 21:46:28 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
if t.resolveDelay == 0 {
|
|
|
|
t.resolveDelay = initialResolveDelay
|
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
if t.lastResolved > 0 && time.Duration(d.clock.Now()-t.lastResolved) < t.resolveDelay {
|
2015-10-22 21:46:28 +00:00
|
|
|
return false
|
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
resolved := d.resolver.Resolve(t.dest)
|
|
|
|
t.lastResolved = d.clock.Now()
|
2015-10-22 21:46:28 +00:00
|
|
|
if resolved == nil {
|
|
|
|
t.resolveDelay *= 2
|
|
|
|
if t.resolveDelay > maxResolveDelay {
|
|
|
|
t.resolveDelay = maxResolveDelay
|
|
|
|
}
|
2021-10-05 01:14:04 +00:00
|
|
|
d.log.Warn("Resolving node failed", "id", t.dest.ID(), "newdelay", t.resolveDelay)
|
2015-10-22 21:46:28 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
// The node was found.
|
|
|
|
t.resolveDelay = initialResolveDelay
|
|
|
|
t.dest = resolved
|
2021-10-05 01:14:04 +00:00
|
|
|
d.log.Trace("Resolved node", "id", t.dest.ID(), "addr", &net.TCPAddr{IP: t.dest.IP(), Port: t.dest.TCP()})
|
2015-10-22 21:46:28 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// dial performs the actual connection attempt.
|
2020-02-13 10:10:03 +00:00
|
|
|
func (t *dialTask) dial(d *dialScheduler, dest *enode.Node) error {
|
|
|
|
fd, err := d.dialer.Dial(d.ctx, t.dest)
|
2015-05-15 22:38:28 +00:00
|
|
|
if err != nil {
|
2023-11-07 08:48:58 +00:00
|
|
|
cleanErr := cleanupDialErr(err)
|
|
|
|
d.log.Trace("Dial error", "id", t.dest.ID(), "addr", nodeAddr(t.dest), "conn", t.flags, "err", cleanErr)
|
|
|
|
|
|
|
|
d.mutex.Lock()
|
|
|
|
d.errors[cleanErr.Error()] = d.errors[cleanErr.Error()] + 1
|
|
|
|
d.mutex.Unlock()
|
2017-12-01 11:49:04 +00:00
|
|
|
return &dialError{err}
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
dashboard: send current block to the dashboard client (#19762)
This adds all dashboard changes from the last couple months.
We're about to remove the dashboard, but decided that we should
get all the recent work in first in case anyone wants to pick up this
project later on.
* cmd, dashboard, eth, p2p: send peer info to the dashboard
* dashboard: update npm packages, improve UI, rebase
* dashboard, p2p: remove println, change doc
* cmd, dashboard, eth, p2p: cleanup after review
* dashboard: send current block to the dashboard client
2019-11-13 11:13:13 +00:00
|
|
|
mfd := newMeteredConn(fd, false, &net.TCPAddr{IP: dest.IP(), Port: dest.TCP()})
|
2020-02-13 10:10:03 +00:00
|
|
|
return d.setupFunc(mfd, t.flags, dest)
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
2015-10-22 21:46:28 +00:00
|
|
|
|
2015-05-15 22:38:28 +00:00
|
|
|
func (t *dialTask) String() string {
|
all: new p2p node representation (#17643)
Package p2p/enode provides a generalized representation of p2p nodes
which can contain arbitrary information in key/value pairs. It is also
the new home for the node database. The "v4" identity scheme is also
moved here from p2p/enr to remove the dependency on Ethereum crypto from
that package.
Record signature handling is changed significantly. The identity scheme
registry is removed and acceptable schemes must be passed to any method
that needs identity. This means records must now be validated explicitly
after decoding.
The enode API is designed to make signature handling easy and safe: most
APIs around the codebase work with enode.Node, which is a wrapper around
a valid record. Going from enr.Record to enode.Node requires a valid
signature.
* p2p/discover: port to p2p/enode
This ports the discovery code to the new node representation in
p2p/enode. The wire protocol is unchanged, this can be considered a
refactoring change. The Kademlia table can now deal with nodes using an
arbitrary identity scheme. This requires a few incompatible API changes:
- Table.Lookup is not available anymore. It used to take a public key
as argument because v4 protocol requires one. Its replacement is
LookupRandom.
- Table.Resolve takes *enode.Node instead of NodeID. This is also for
v4 protocol compatibility because nodes cannot be looked up by ID
alone.
- Types Node and NodeID are gone. Further commits in the series will be
fixes all over the the codebase to deal with those removals.
* p2p: port to p2p/enode and discovery changes
This adapts package p2p to the changes in p2p/discover. All uses of
discover.Node and discover.NodeID are replaced by their equivalents from
p2p/enode.
New API is added to retrieve the enode.Node instance of a peer. The
behavior of Server.Self with discovery disabled is improved. It now
tries much harder to report a working IP address, falling back to
127.0.0.1 if no suitable address can be determined through other means.
These changes were needed for tests of other packages later in the
series.
* p2p/simulations, p2p/testing: port to p2p/enode
No surprises here, mostly replacements of discover.Node, discover.NodeID
with their new equivalents. The 'interesting' API changes are:
- testing.ProtocolSession tracks complete nodes, not just their IDs.
- adapters.NodeConfig has a new method to create a complete node.
These changes were needed to make swarm tests work.
Note that the NodeID change makes the code incompatible with old
simulation snapshots.
* whisper/whisperv5, whisper/whisperv6: port to p2p/enode
This port was easy because whisper uses []byte for node IDs and
URL strings in the API.
* eth: port to p2p/enode
Again, easy to port because eth uses strings for node IDs and doesn't
care about node information in any way.
* les: port to p2p/enode
Apart from replacing discover.NodeID with enode.ID, most changes are in
the server pool code. It now deals with complete nodes instead
of (Pubkey, IP, Port) triples. The database format is unchanged for now,
but we should probably change it to use the node database later.
* node: port to p2p/enode
This change simply replaces discover.Node and discover.NodeID with their
new equivalents.
* swarm/network: port to p2p/enode
Swarm has its own node address representation, BzzAddr, containing both
an overlay address (the hash of a secp256k1 public key) and an underlay
address (enode:// URL).
There are no changes to the BzzAddr format in this commit, but certain
operations such as creating a BzzAddr from a node ID are now impossible
because node IDs aren't public keys anymore.
Most swarm-related changes in the series remove uses of
NewAddrFromNodeID, replacing it with NewAddr which takes a complete node
as argument. ToOverlayAddr is removed because we can just use the node
ID directly.
2018-09-24 22:59:00 +00:00
|
|
|
id := t.dest.ID()
|
|
|
|
return fmt.Sprintf("%v %x %v:%d", t.flags, id[:8], t.dest.IP(), t.dest.TCP())
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
|
|
|
|
2020-02-13 10:10:03 +00:00
|
|
|
func cleanupDialErr(err error) error {
|
|
|
|
if netErr, ok := err.(*net.OpError); ok && netErr.Op == "dial" {
|
|
|
|
return netErr.Err
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|
2020-02-13 10:10:03 +00:00
|
|
|
return err
|
2015-05-15 22:38:28 +00:00
|
|
|
}
|