github.com/EgonCoin/EgonChain@v1.10.16/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/EgonCoin/EgonChain/common/mclock" 31 "github.com/EgonCoin/EgonChain/log" 32 "github.com/EgonCoin/EgonChain/p2p/enode" 33 "github.com/EgonCoin/EgonChain/p2p/netutil" 34 ) 35 36 const ( 37 // This is the amount of time spent waiting in between redialing a certain node. The 38 // limit is a bit higher than inboundThrottleTime to prevent failing dials in small 39 // private networks. 40 dialHistoryExpiration = inboundThrottleTime + 5*time.Second 41 42 // Config for the "Looking for peers" message. 43 dialStatsLogInterval = 10 * time.Second // printed at most this often 44 dialStatsPeerLimit = 3 // but not if more than this many dialed peers 45 46 // Endpoint resolution is throttled with bounded backoff. 47 initialResolveDelay = 60 * time.Second 48 maxResolveDelay = time.Hour 49 ) 50 51 // NodeDialer is used to connect to nodes in the network, typically by using 52 // an underlying net.Dialer but also using net.Pipe in tests. 53 type NodeDialer interface { 54 Dial(context.Context, *enode.Node) (net.Conn, error) 55 } 56 57 type nodeResolver interface { 58 Resolve(*enode.Node) *enode.Node 59 } 60 61 // tcpDialer implements NodeDialer using real TCP connections. 62 type tcpDialer struct { 63 d *net.Dialer 64 } 65 66 func (t tcpDialer) Dial(ctx context.Context, dest *enode.Node) (net.Conn, error) { 67 return t.d.DialContext(ctx, "tcp", nodeAddr(dest).String()) 68 } 69 70 func nodeAddr(n *enode.Node) net.Addr { 71 return &net.TCPAddr{IP: n.IP(), Port: n.TCP()} 72 } 73 74 // checkDial errors: 75 var ( 76 errSelf = errors.New("is self") 77 errAlreadyDialing = errors.New("already dialing") 78 errAlreadyConnected = errors.New("already connected") 79 errRecentlyDialed = errors.New("recently dialed") 80 errNetRestrict = errors.New("not contained in netrestrict list") 81 errNoPort = errors.New("node does not provide TCP port") 82 ) 83 84 // dialer creates outbound connections and submits them into Server. 85 // Two types of peer connections can be created: 86 // 87 // - static dials are pre-configured connections. The dialer attempts 88 // keep these nodes connected at all times. 89 // 90 // - dynamic dials are created from node discovery results. The dialer 91 // continuously reads candidate nodes from its input iterator and attempts 92 // to create peer connections to nodes arriving through the iterator. 93 // 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]struct{} // 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.Root() 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]struct{}), 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] = struct{}{} 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.Trace("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 } 341 d.doneSinceLastLog = 0 342 d.lastStatsLog = now 343 } 344 345 // rearmHistoryTimer configures d.historyTimer to fire when the 346 // next item in d.history expires. 347 func (d *dialScheduler) rearmHistoryTimer(ch chan struct{}) { 348 if len(d.history) == 0 || d.historyTimerTime == d.history.nextExpiry() { 349 return 350 } 351 d.stopHistoryTimer(ch) 352 d.historyTimerTime = d.history.nextExpiry() 353 timeout := time.Duration(d.historyTimerTime - d.clock.Now()) 354 d.historyTimer = d.clock.AfterFunc(timeout, func() { ch <- struct{}{} }) 355 } 356 357 // stopHistoryTimer stops the timer and drains the channel it sends on. 358 func (d *dialScheduler) stopHistoryTimer(ch chan struct{}) { 359 if d.historyTimer != nil && !d.historyTimer.Stop() { 360 <-ch 361 } 362 } 363 364 // expireHistory removes expired items from d.history. 365 func (d *dialScheduler) expireHistory() { 366 d.historyTimer.Stop() 367 d.historyTimer = nil 368 d.historyTimerTime = 0 369 d.history.expire(d.clock.Now(), func(hkey string) { 370 var id enode.ID 371 copy(id[:], hkey) 372 d.updateStaticPool(id) 373 }) 374 } 375 376 // freeDialSlots returns the number of free dial slots. The result can be negative 377 // when peers are connected while their task is still running. 378 func (d *dialScheduler) freeDialSlots() int { 379 slots := (d.maxDialPeers - d.dialPeers) * 2 380 if slots > d.maxActiveDials { 381 slots = d.maxActiveDials 382 } 383 free := slots - len(d.dialing) 384 return free 385 } 386 387 // checkDial returns an error if node n should not be dialed. 388 func (d *dialScheduler) checkDial(n *enode.Node) error { 389 if n.ID() == d.self { 390 return errSelf 391 } 392 if n.IP() != nil && n.TCP() == 0 { 393 // This check can trigger if a non-TCP node is found 394 // by discovery. If there is no IP, the node is a static 395 // node and the actual endpoint will be resolved later in dialTask. 396 return errNoPort 397 } 398 if _, ok := d.dialing[n.ID()]; ok { 399 return errAlreadyDialing 400 } 401 if _, ok := d.peers[n.ID()]; ok { 402 return errAlreadyConnected 403 } 404 if d.netRestrict != nil && !d.netRestrict.Contains(n.IP()) { 405 return errNetRestrict 406 } 407 if d.history.contains(string(n.ID().Bytes())) { 408 return errRecentlyDialed 409 } 410 return nil 411 } 412 413 // startStaticDials starts n static dial tasks. 414 func (d *dialScheduler) startStaticDials(n int) (started int) { 415 for started = 0; started < n && len(d.staticPool) > 0; started++ { 416 idx := d.rand.Intn(len(d.staticPool)) 417 task := d.staticPool[idx] 418 d.startDial(task) 419 d.removeFromStaticPool(idx) 420 } 421 return started 422 } 423 424 // updateStaticPool attempts to move the given static dial back into staticPool. 425 func (d *dialScheduler) updateStaticPool(id enode.ID) { 426 task, ok := d.static[id] 427 if ok && task.staticPoolIndex < 0 && d.checkDial(task.dest) == nil { 428 d.addToStaticPool(task) 429 } 430 } 431 432 func (d *dialScheduler) addToStaticPool(task *dialTask) { 433 if task.staticPoolIndex >= 0 { 434 panic("attempt to add task to staticPool twice") 435 } 436 d.staticPool = append(d.staticPool, task) 437 task.staticPoolIndex = len(d.staticPool) - 1 438 } 439 440 // removeFromStaticPool removes the task at idx from staticPool. It does that by moving the 441 // current last element of the pool to idx and then shortening the pool by one. 442 func (d *dialScheduler) removeFromStaticPool(idx int) { 443 task := d.staticPool[idx] 444 end := len(d.staticPool) - 1 445 d.staticPool[idx] = d.staticPool[end] 446 d.staticPool[idx].staticPoolIndex = idx 447 d.staticPool[end] = nil 448 d.staticPool = d.staticPool[:end] 449 task.staticPoolIndex = -1 450 } 451 452 // startDial runs the given dial task in a separate goroutine. 453 func (d *dialScheduler) startDial(task *dialTask) { 454 d.log.Trace("Starting p2p dial", "id", task.dest.ID(), "ip", task.dest.IP(), "flag", task.flags) 455 hkey := string(task.dest.ID().Bytes()) 456 d.history.add(hkey, d.clock.Now().Add(dialHistoryExpiration)) 457 d.dialing[task.dest.ID()] = task 458 go func() { 459 task.run(d) 460 d.doneCh <- task 461 }() 462 } 463 464 // A dialTask generated for each node that is dialed. 465 type dialTask struct { 466 staticPoolIndex int 467 flags connFlag 468 // These fields are private to the task and should not be 469 // accessed by dialScheduler while the task is running. 470 dest *enode.Node 471 lastResolved mclock.AbsTime 472 resolveDelay time.Duration 473 } 474 475 func newDialTask(dest *enode.Node, flags connFlag) *dialTask { 476 return &dialTask{dest: dest, flags: flags, staticPoolIndex: -1} 477 } 478 479 type dialError struct { 480 error 481 } 482 483 func (t *dialTask) run(d *dialScheduler) { 484 if t.needResolve() && !t.resolve(d) { 485 return 486 } 487 488 err := t.dial(d, t.dest) 489 if err != nil { 490 // For static nodes, resolve one more time if dialing fails. 491 if _, ok := err.(*dialError); ok && t.flags&staticDialedConn != 0 { 492 if t.resolve(d) { 493 t.dial(d, t.dest) 494 } 495 } 496 } 497 } 498 499 func (t *dialTask) needResolve() bool { 500 return t.flags&staticDialedConn != 0 && t.dest.IP() == nil 501 } 502 503 // resolve attempts to find the current endpoint for the destination 504 // using discovery. 505 // 506 // Resolve operations are throttled with backoff to avoid flooding the 507 // discovery network with useless queries for nodes that don't exist. 508 // The backoff delay resets when the node is found. 509 func (t *dialTask) resolve(d *dialScheduler) bool { 510 if d.resolver == nil { 511 return false 512 } 513 if t.resolveDelay == 0 { 514 t.resolveDelay = initialResolveDelay 515 } 516 if t.lastResolved > 0 && time.Duration(d.clock.Now()-t.lastResolved) < t.resolveDelay { 517 return false 518 } 519 resolved := d.resolver.Resolve(t.dest) 520 t.lastResolved = d.clock.Now() 521 if resolved == nil { 522 t.resolveDelay *= 2 523 if t.resolveDelay > maxResolveDelay { 524 t.resolveDelay = maxResolveDelay 525 } 526 d.log.Debug("Resolving node failed", "id", t.dest.ID(), "newdelay", t.resolveDelay) 527 return false 528 } 529 // The node was found. 530 t.resolveDelay = initialResolveDelay 531 t.dest = resolved 532 d.log.Debug("Resolved node", "id", t.dest.ID(), "addr", &net.TCPAddr{IP: t.dest.IP(), Port: t.dest.TCP()}) 533 return true 534 } 535 536 // dial performs the actual connection attempt. 537 func (t *dialTask) dial(d *dialScheduler, dest *enode.Node) error { 538 fd, err := d.dialer.Dial(d.ctx, t.dest) 539 if err != nil { 540 d.log.Trace("Dial error", "id", t.dest.ID(), "addr", nodeAddr(t.dest), "conn", t.flags, "err", cleanupDialErr(err)) 541 return &dialError{err} 542 } 543 mfd := newMeteredConn(fd, false, &net.TCPAddr{IP: dest.IP(), Port: dest.TCP()}) 544 return d.setupFunc(mfd, t.flags, dest) 545 } 546 547 func (t *dialTask) String() string { 548 id := t.dest.ID() 549 return fmt.Sprintf("%v %x %v:%d", t.flags, id[:8], t.dest.IP(), t.dest.TCP()) 550 } 551 552 func cleanupDialErr(err error) error { 553 if netErr, ok := err.(*net.OpError); ok && netErr.Op == "dial" { 554 return netErr.Err 555 } 556 return err 557 }