github.com/dominant-strategies/go-quai@v0.28.2/p2p/dial.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package p2p 18 19 import ( 20 "context" 21 crand "crypto/rand" 22 "encoding/binary" 23 "errors" 24 "fmt" 25 mrand "math/rand" 26 "net" 27 "sync" 28 "time" 29 30 "github.com/dominant-strategies/go-quai/common" 31 "github.com/dominant-strategies/go-quai/common/mclock" 32 "github.com/dominant-strategies/go-quai/log" 33 "github.com/dominant-strategies/go-quai/p2p/enode" 34 "github.com/dominant-strategies/go-quai/p2p/netutil" 35 ) 36 37 const ( 38 // This is the amount of time spent waiting in between redialing a certain node. The 39 // limit is a bit higher than inboundThrottleTime to prevent failing dials in small 40 // private networks. 41 dialHistoryExpiration = inboundThrottleTime + 5*time.Second 42 43 // Config for the "Looking for peers" message. 44 dialStatsLogInterval = 60 * time.Second // printed at most this often 45 dialStatsPeerLimit = 3 // but not if more than this many dialed peers 46 47 // Endpoint resolution is throttled with bounded backoff. 48 initialResolveDelay = 60 * time.Second 49 maxResolveDelay = time.Hour 50 ) 51 52 // NodeDialer is used to connect to nodes in the network, typically by using 53 // an underlying net.Dialer but also using net.Pipe in tests. 54 type NodeDialer interface { 55 Dial(context.Context, *enode.Node) (net.Conn, error) 56 } 57 58 type nodeResolver interface { 59 Resolve(*enode.Node) *enode.Node 60 } 61 62 // tcpDialer implements NodeDialer using real TCP connections. 63 type tcpDialer struct { 64 d *net.Dialer 65 } 66 67 func (t tcpDialer) Dial(ctx context.Context, dest *enode.Node) (net.Conn, error) { 68 return t.d.DialContext(ctx, "tcp", nodeAddr(dest).String()) 69 } 70 71 func nodeAddr(n *enode.Node) net.Addr { 72 return &net.TCPAddr{IP: n.IP(), Port: n.TCP()} 73 } 74 75 // checkDial errors: 76 var ( 77 errSelf = errors.New("is self") 78 errAlreadyDialing = errors.New("already dialing") 79 errAlreadyConnected = errors.New("already connected") 80 errRecentlyDialed = errors.New("recently dialed") 81 errNetRestrict = errors.New("not contained in netrestrict list") 82 errNoPort = errors.New("node does not provide TCP port") 83 ) 84 85 // dialer creates outbound connections and submits them into Server. 86 // Two types of peer connections can be created: 87 // 88 // - static dials are pre-configured connections. The dialer attempts 89 // keep these nodes connected at all times. 90 // 91 // - dynamic dials are created from node discovery results. The dialer 92 // continuously reads candidate nodes from its input iterator and attempts 93 // to create peer connections to nodes arriving through the iterator. 94 type dialScheduler struct { 95 dialConfig 96 setupFunc dialSetupFunc 97 wg sync.WaitGroup 98 cancel context.CancelFunc 99 ctx context.Context 100 nodesIn chan *enode.Node 101 doneCh chan *dialTask 102 addStaticCh chan *enode.Node 103 remStaticCh chan *enode.Node 104 addPeerCh chan *conn 105 remPeerCh chan *conn 106 107 // Everything below here belongs to loop and 108 // should only be accessed by code on the loop goroutine. 109 dialing map[enode.ID]*dialTask // active tasks 110 peers map[enode.ID]connFlag // all connected peers 111 dialPeers int // current number of dialed peers 112 113 // The static map tracks all static dial tasks. The subset of usable static dial tasks 114 // (i.e. those passing checkDial) is kept in staticPool. The scheduler prefers 115 // launching random static tasks from the pool over launching dynamic dials from the 116 // iterator. 117 static map[enode.ID]*dialTask 118 staticPool []*dialTask 119 120 // The dial history keeps recently dialed nodes. Members of history are not dialed. 121 history expHeap 122 historyTimer mclock.Timer 123 historyTimerTime mclock.AbsTime 124 125 // for logStats 126 lastStatsLog mclock.AbsTime 127 doneSinceLastLog int 128 } 129 130 type dialSetupFunc func(net.Conn, connFlag, *enode.Node) error 131 132 type dialConfig struct { 133 self enode.ID // our own ID 134 maxDialPeers int // maximum number of dialed peers 135 maxActiveDials int // maximum number of active dials 136 netRestrict *netutil.Netlist // IP netrestrict list, disabled if nil 137 resolver nodeResolver 138 dialer NodeDialer 139 log *log.Logger 140 clock mclock.Clock 141 rand *mrand.Rand 142 } 143 144 func (cfg dialConfig) withDefaults() dialConfig { 145 if cfg.maxActiveDials == 0 { 146 cfg.maxActiveDials = defaultMaxPendingPeers 147 } 148 if cfg.log == nil { 149 cfg.log = &log.Log 150 } 151 if cfg.clock == nil { 152 cfg.clock = mclock.System{} 153 } 154 if cfg.rand == nil { 155 seedb := make([]byte, 8) 156 crand.Read(seedb) 157 seed := int64(binary.BigEndian.Uint64(seedb)) 158 cfg.rand = mrand.New(mrand.NewSource(seed)) 159 } 160 return cfg 161 } 162 163 func newDialScheduler(config dialConfig, it enode.Iterator, setupFunc dialSetupFunc) *dialScheduler { 164 d := &dialScheduler{ 165 dialConfig: config.withDefaults(), 166 setupFunc: setupFunc, 167 dialing: make(map[enode.ID]*dialTask), 168 static: make(map[enode.ID]*dialTask), 169 peers: make(map[enode.ID]connFlag), 170 doneCh: make(chan *dialTask), 171 nodesIn: make(chan *enode.Node), 172 addStaticCh: make(chan *enode.Node), 173 remStaticCh: make(chan *enode.Node), 174 addPeerCh: make(chan *conn), 175 remPeerCh: make(chan *conn), 176 } 177 d.lastStatsLog = d.clock.Now() 178 d.ctx, d.cancel = context.WithCancel(context.Background()) 179 d.wg.Add(2) 180 go d.readNodes(it) 181 go d.loop(it) 182 return d 183 } 184 185 // stop shuts down the dialer, canceling all current dial tasks. 186 func (d *dialScheduler) stop() { 187 d.cancel() 188 d.wg.Wait() 189 } 190 191 // addStatic adds a static dial candidate. 192 func (d *dialScheduler) addStatic(n *enode.Node) { 193 select { 194 case d.addStaticCh <- n: 195 case <-d.ctx.Done(): 196 } 197 } 198 199 // removeStatic removes a static dial candidate. 200 func (d *dialScheduler) removeStatic(n *enode.Node) { 201 select { 202 case d.remStaticCh <- n: 203 case <-d.ctx.Done(): 204 } 205 } 206 207 // peerAdded updates the peer set. 208 func (d *dialScheduler) peerAdded(c *conn) { 209 select { 210 case d.addPeerCh <- c: 211 case <-d.ctx.Done(): 212 } 213 } 214 215 // peerRemoved updates the peer set. 216 func (d *dialScheduler) peerRemoved(c *conn) { 217 select { 218 case d.remPeerCh <- c: 219 case <-d.ctx.Done(): 220 } 221 } 222 223 // loop is the main loop of the dialer. 224 func (d *dialScheduler) loop(it enode.Iterator) { 225 var ( 226 nodesCh chan *enode.Node 227 historyExp = make(chan struct{}, 1) 228 ) 229 230 loop: 231 for { 232 // Launch new dials if slots are available. 233 slots := d.freeDialSlots() 234 slots -= d.startStaticDials(slots) 235 if slots > 0 { 236 nodesCh = d.nodesIn 237 } else { 238 nodesCh = nil 239 } 240 d.rearmHistoryTimer(historyExp) 241 d.logStats() 242 243 select { 244 case node := <-nodesCh: 245 if err := d.checkDial(node); err != nil { 246 d.log.Trace("Discarding dial candidate", "id", node.ID(), "ip", node.IP(), "reason", err) 247 } else { 248 d.startDial(newDialTask(node, dynDialedConn)) 249 } 250 251 case task := <-d.doneCh: 252 id := task.dest.ID() 253 delete(d.dialing, id) 254 d.updateStaticPool(id) 255 d.doneSinceLastLog++ 256 257 case c := <-d.addPeerCh: 258 if c.is(dynDialedConn) || c.is(staticDialedConn) { 259 d.dialPeers++ 260 } 261 id := c.node.ID() 262 d.peers[id] = c.flags 263 // Remove from static pool because the node is now connected. 264 task := d.static[id] 265 if task != nil && task.staticPoolIndex >= 0 { 266 d.removeFromStaticPool(task.staticPoolIndex) 267 } 268 // TODO: cancel dials to connected peers 269 270 case c := <-d.remPeerCh: 271 if c.is(dynDialedConn) || c.is(staticDialedConn) { 272 d.dialPeers-- 273 } 274 delete(d.peers, c.node.ID()) 275 d.updateStaticPool(c.node.ID()) 276 277 case node := <-d.addStaticCh: 278 id := node.ID() 279 _, exists := d.static[id] 280 d.log.Info("Adding static node", "id", id, "ip", node.IP(), "added", !exists) 281 if exists { 282 continue loop 283 } 284 task := newDialTask(node, staticDialedConn) 285 d.static[id] = task 286 if d.checkDial(node) == nil { 287 d.addToStaticPool(task) 288 } 289 290 case node := <-d.remStaticCh: 291 id := node.ID() 292 task := d.static[id] 293 d.log.Trace("Removing static node", "id", id, "ok", task != nil) 294 if task != nil { 295 delete(d.static, id) 296 if task.staticPoolIndex >= 0 { 297 d.removeFromStaticPool(task.staticPoolIndex) 298 } 299 } 300 301 case <-historyExp: 302 d.expireHistory() 303 304 case <-d.ctx.Done(): 305 it.Close() 306 break loop 307 } 308 } 309 310 d.stopHistoryTimer(historyExp) 311 for range d.dialing { 312 <-d.doneCh 313 } 314 d.wg.Done() 315 } 316 317 // readNodes runs in its own goroutine and delivers nodes from 318 // the input iterator to the nodesIn channel. 319 func (d *dialScheduler) readNodes(it enode.Iterator) { 320 defer d.wg.Done() 321 322 for it.Next() { 323 select { 324 case d.nodesIn <- it.Node(): 325 case <-d.ctx.Done(): 326 } 327 } 328 } 329 330 // logStats prints dialer statistics to the log. The message is suppressed when enough 331 // peers are connected because users should only see it while their client is starting up 332 // or comes back online. 333 func (d *dialScheduler) logStats() { 334 now := d.clock.Now() 335 if d.lastStatsLog.Add(dialStatsLogInterval) > now { 336 return 337 } 338 if d.dialPeers < dialStatsPeerLimit && d.dialPeers < d.maxDialPeers { 339 d.log.Info("Looking for peers", "peercount", len(d.peers), "tried", d.doneSinceLastLog, "static", len(d.static)) 340 if common.NodeLocation.Context() == common.PRIME_CTX && len(d.peers) < 3 { 341 d.log.Info("Prime chain needs at least 3 peers to start the sync, it may take up to 30 mins in some cases to meet the requirement") 342 } 343 } else { 344 d.log.Info("Peer info", "peers", len(d.peers), "tried", d.doneSinceLastLog, "static", len(d.static)) 345 } 346 d.doneSinceLastLog = 0 347 d.lastStatsLog = now 348 } 349 350 // rearmHistoryTimer configures d.historyTimer to fire when the 351 // next item in d.history expires. 352 func (d *dialScheduler) rearmHistoryTimer(ch chan struct{}) { 353 if len(d.history) == 0 || d.historyTimerTime == d.history.nextExpiry() { 354 return 355 } 356 d.stopHistoryTimer(ch) 357 d.historyTimerTime = d.history.nextExpiry() 358 timeout := time.Duration(d.historyTimerTime - d.clock.Now()) 359 d.historyTimer = d.clock.AfterFunc(timeout, func() { ch <- struct{}{} }) 360 } 361 362 // stopHistoryTimer stops the timer and drains the channel it sends on. 363 func (d *dialScheduler) stopHistoryTimer(ch chan struct{}) { 364 if d.historyTimer != nil && !d.historyTimer.Stop() { 365 <-ch 366 } 367 } 368 369 // expireHistory removes expired items from d.history. 370 func (d *dialScheduler) expireHistory() { 371 d.historyTimer.Stop() 372 d.historyTimer = nil 373 d.historyTimerTime = 0 374 d.history.expire(d.clock.Now(), func(hkey string) { 375 var id enode.ID 376 copy(id[:], hkey) 377 d.updateStaticPool(id) 378 }) 379 } 380 381 // freeDialSlots returns the number of free dial slots. The result can be negative 382 // when peers are connected while their task is still running. 383 func (d *dialScheduler) freeDialSlots() int { 384 slots := (d.maxDialPeers - d.dialPeers) * 2 385 if slots > d.maxActiveDials { 386 slots = d.maxActiveDials 387 } 388 free := slots - len(d.dialing) 389 return free 390 } 391 392 // checkDial returns an error if node n should not be dialed. 393 func (d *dialScheduler) checkDial(n *enode.Node) error { 394 if n.ID() == d.self { 395 return errSelf 396 } 397 if n.IP() != nil && n.TCP() == 0 { 398 // This check can trigger if a non-TCP node is found 399 // by discovery. If there is no IP, the node is a static 400 // node and the actual endpoint will be resolved later in dialTask. 401 return errNoPort 402 } 403 if _, ok := d.dialing[n.ID()]; ok { 404 return errAlreadyDialing 405 } 406 if _, ok := d.peers[n.ID()]; ok { 407 return errAlreadyConnected 408 } 409 if d.netRestrict != nil && !d.netRestrict.Contains(n.IP()) { 410 return errNetRestrict 411 } 412 if d.history.contains(string(n.ID().Bytes())) { 413 return errRecentlyDialed 414 } 415 return nil 416 } 417 418 // startStaticDials starts n static dial tasks. 419 func (d *dialScheduler) startStaticDials(n int) (started int) { 420 for started = 0; started < n && len(d.staticPool) > 0; started++ { 421 idx := d.rand.Intn(len(d.staticPool)) 422 task := d.staticPool[idx] 423 d.startDial(task) 424 d.removeFromStaticPool(idx) 425 } 426 return started 427 } 428 429 // updateStaticPool attempts to move the given static dial back into staticPool. 430 func (d *dialScheduler) updateStaticPool(id enode.ID) { 431 task, ok := d.static[id] 432 if ok && task.staticPoolIndex < 0 && d.checkDial(task.dest) == nil { 433 d.addToStaticPool(task) 434 } 435 } 436 437 func (d *dialScheduler) addToStaticPool(task *dialTask) { 438 if task.staticPoolIndex >= 0 { 439 panic("attempt to add task to staticPool twice") 440 } 441 d.staticPool = append(d.staticPool, task) 442 task.staticPoolIndex = len(d.staticPool) - 1 443 } 444 445 // removeFromStaticPool removes the task at idx from staticPool. It does that by moving the 446 // current last element of the pool to idx and then shortening the pool by one. 447 func (d *dialScheduler) removeFromStaticPool(idx int) { 448 task := d.staticPool[idx] 449 end := len(d.staticPool) - 1 450 d.staticPool[idx] = d.staticPool[end] 451 d.staticPool[idx].staticPoolIndex = idx 452 d.staticPool[end] = nil 453 d.staticPool = d.staticPool[:end] 454 task.staticPoolIndex = -1 455 } 456 457 // startDial runs the given dial task in a separate goroutine. 458 func (d *dialScheduler) startDial(task *dialTask) { 459 d.log.Trace("Starting p2p dial", "id", task.dest.ID(), "ip", task.dest.IP(), "flag", task.flags) 460 hkey := string(task.dest.ID().Bytes()) 461 d.history.add(hkey, d.clock.Now().Add(dialHistoryExpiration)) 462 d.dialing[task.dest.ID()] = task 463 go func() { 464 task.run(d) 465 d.doneCh <- task 466 }() 467 } 468 469 // A dialTask generated for each node that is dialed. 470 type dialTask struct { 471 staticPoolIndex int 472 flags connFlag 473 // These fields are private to the task and should not be 474 // accessed by dialScheduler while the task is running. 475 dest *enode.Node 476 lastResolved mclock.AbsTime 477 resolveDelay time.Duration 478 } 479 480 func newDialTask(dest *enode.Node, flags connFlag) *dialTask { 481 return &dialTask{dest: dest, flags: flags, staticPoolIndex: -1} 482 } 483 484 type dialError struct { 485 error 486 } 487 488 func (t *dialTask) run(d *dialScheduler) { 489 if t.needResolve() && !t.resolve(d) { 490 return 491 } 492 493 err := t.dial(d, t.dest) 494 if err != nil { 495 // For static nodes, resolve one more time if dialing fails. 496 if _, ok := err.(*dialError); ok && t.flags&staticDialedConn != 0 { 497 if t.resolve(d) { 498 t.dial(d, t.dest) 499 } 500 } 501 } 502 } 503 504 func (t *dialTask) needResolve() bool { 505 return t.flags&staticDialedConn != 0 && t.dest.IP() == nil 506 } 507 508 // resolve attempts to find the current endpoint for the destination 509 // using discovery. 510 // 511 // Resolve operations are throttled with backoff to avoid flooding the 512 // discovery network with useless queries for nodes that don't exist. 513 // The backoff delay resets when the node is found. 514 func (t *dialTask) resolve(d *dialScheduler) bool { 515 if d.resolver == nil { 516 return false 517 } 518 if t.resolveDelay == 0 { 519 t.resolveDelay = initialResolveDelay 520 } 521 if t.lastResolved > 0 && time.Duration(d.clock.Now()-t.lastResolved) < t.resolveDelay { 522 return false 523 } 524 resolved := d.resolver.Resolve(t.dest) 525 t.lastResolved = d.clock.Now() 526 if resolved == nil { 527 t.resolveDelay *= 2 528 if t.resolveDelay > maxResolveDelay { 529 t.resolveDelay = maxResolveDelay 530 } 531 d.log.Debug("Resolving node failed", "id", t.dest.ID(), "newdelay", t.resolveDelay) 532 return false 533 } 534 // The node was found. 535 t.resolveDelay = initialResolveDelay 536 t.dest = resolved 537 d.log.Debug("Resolved node", "id", t.dest.ID(), "addr", &net.TCPAddr{IP: t.dest.IP(), Port: t.dest.TCP()}) 538 return true 539 } 540 541 // dial performs the actual connection attempt. 542 func (t *dialTask) dial(d *dialScheduler, dest *enode.Node) error { 543 fd, err := d.dialer.Dial(d.ctx, t.dest) 544 if err != nil { 545 d.log.Trace("Dial error", "id", t.dest.ID(), "addr", nodeAddr(t.dest), "conn", t.flags, "err", cleanupDialErr(err)) 546 return &dialError{err} 547 } 548 mfd := newMeteredConn(fd, false, &net.TCPAddr{IP: dest.IP(), Port: dest.TCP()}) 549 return d.setupFunc(mfd, t.flags, dest) 550 } 551 552 func (t *dialTask) String() string { 553 id := t.dest.ID() 554 return fmt.Sprintf("%v %x %v:%d", t.flags, id[:8], t.dest.IP(), t.dest.TCP()) 555 } 556 557 func cleanupDialErr(err error) error { 558 if netErr, ok := err.(*net.OpError); ok && netErr.Op == "dial" { 559 return netErr.Err 560 } 561 return err 562 }