You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

576 lines
15 KiB

9 years ago
9 years ago
8 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
8 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
p2p: introduce peerConn to simplify peer creation (#1226) * expose AuthEnc in the P2P config if AuthEnc is true, dialed peers must have a node ID in the address and it must match the persistent pubkey from the secret handshake. Refs #1157 * fixes after my own review * fix docs * fix build failure ``` p2p/pex/pex_reactor_test.go:288:88: cannot use seed.NodeInfo().NetAddress() (type *p2p.NetAddress) as type string in array or slice literal ``` * p2p: introduce peerConn to simplify peer creation * Introduce `peerConn` containing the known fields of `peer` * `peer` only created in `sw.addPeer` once handshake is complete and NodeInfo is checked * Eliminates some mutable variables and makes the code flow better * Simplifies the `newXxxPeer` funcs * Use ID instead of PubKey where possible. * SetPubKeyFilter -> SetIDFilter * nodeInfo.Validate takes ID * remove peer.PubKey() * persistent node ids * fixes from review * test: use ip_plus_id.sh more * fix invalid memory panic during fast_sync test ``` 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: panic: runtime error: invalid memory address or nil pointer dereference 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x98dd3e] 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: goroutine 3432 [running]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.newOutboundPeerConn(0xc423fd1380, 0xc420933e00, 0x1, 0x1239a60, 0 xc420128c40, 0x2, 0x42caf6, 0xc42001f300, 0xc422831d98, 0xc4227951c0, ...) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/peer.go:123 +0x31e 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).addOutboundPeerWithConfig(0xc4200ad040, 0xc423fd1380, 0 xc420933e00, 0xc423f48801, 0x28, 0x2) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:455 +0x12b 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).DialPeerWithAddress(0xc4200ad040, 0xc423fd1380, 0x1, 0x 0, 0x0) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:371 +0xdc 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).reconnectToPeer(0xc4200ad040, 0x123e000, 0xc42007bb00) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:290 +0x25f 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: created by github.com/tendermint/tendermint/p2p.(*Switch).StopPeerForError 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:256 +0x1b7 ```
7 years ago
9 years ago
p2p: introduce peerConn to simplify peer creation (#1226) * expose AuthEnc in the P2P config if AuthEnc is true, dialed peers must have a node ID in the address and it must match the persistent pubkey from the secret handshake. Refs #1157 * fixes after my own review * fix docs * fix build failure ``` p2p/pex/pex_reactor_test.go:288:88: cannot use seed.NodeInfo().NetAddress() (type *p2p.NetAddress) as type string in array or slice literal ``` * p2p: introduce peerConn to simplify peer creation * Introduce `peerConn` containing the known fields of `peer` * `peer` only created in `sw.addPeer` once handshake is complete and NodeInfo is checked * Eliminates some mutable variables and makes the code flow better * Simplifies the `newXxxPeer` funcs * Use ID instead of PubKey where possible. * SetPubKeyFilter -> SetIDFilter * nodeInfo.Validate takes ID * remove peer.PubKey() * persistent node ids * fixes from review * test: use ip_plus_id.sh more * fix invalid memory panic during fast_sync test ``` 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: panic: runtime error: invalid memory address or nil pointer dereference 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x98dd3e] 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: goroutine 3432 [running]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.newOutboundPeerConn(0xc423fd1380, 0xc420933e00, 0x1, 0x1239a60, 0 xc420128c40, 0x2, 0x42caf6, 0xc42001f300, 0xc422831d98, 0xc4227951c0, ...) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/peer.go:123 +0x31e 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).addOutboundPeerWithConfig(0xc4200ad040, 0xc423fd1380, 0 xc420933e00, 0xc423f48801, 0x28, 0x2) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:455 +0x12b 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).DialPeerWithAddress(0xc4200ad040, 0xc423fd1380, 0x1, 0x 0, 0x0) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:371 +0xdc 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).reconnectToPeer(0xc4200ad040, 0x123e000, 0xc42007bb00) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:290 +0x25f 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: created by github.com/tendermint/tendermint/p2p.(*Switch).StopPeerForError 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:256 +0x1b7 ```
7 years ago
9 years ago
9 years ago
9 years ago
p2p: introduce peerConn to simplify peer creation (#1226) * expose AuthEnc in the P2P config if AuthEnc is true, dialed peers must have a node ID in the address and it must match the persistent pubkey from the secret handshake. Refs #1157 * fixes after my own review * fix docs * fix build failure ``` p2p/pex/pex_reactor_test.go:288:88: cannot use seed.NodeInfo().NetAddress() (type *p2p.NetAddress) as type string in array or slice literal ``` * p2p: introduce peerConn to simplify peer creation * Introduce `peerConn` containing the known fields of `peer` * `peer` only created in `sw.addPeer` once handshake is complete and NodeInfo is checked * Eliminates some mutable variables and makes the code flow better * Simplifies the `newXxxPeer` funcs * Use ID instead of PubKey where possible. * SetPubKeyFilter -> SetIDFilter * nodeInfo.Validate takes ID * remove peer.PubKey() * persistent node ids * fixes from review * test: use ip_plus_id.sh more * fix invalid memory panic during fast_sync test ``` 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: panic: runtime error: invalid memory address or nil pointer dereference 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x98dd3e] 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: goroutine 3432 [running]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.newOutboundPeerConn(0xc423fd1380, 0xc420933e00, 0x1, 0x1239a60, 0 xc420128c40, 0x2, 0x42caf6, 0xc42001f300, 0xc422831d98, 0xc4227951c0, ...) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/peer.go:123 +0x31e 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).addOutboundPeerWithConfig(0xc4200ad040, 0xc423fd1380, 0 xc420933e00, 0xc423f48801, 0x28, 0x2) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:455 +0x12b 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).DialPeerWithAddress(0xc4200ad040, 0xc423fd1380, 0x1, 0x 0, 0x0) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:371 +0xdc 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).reconnectToPeer(0xc4200ad040, 0x123e000, 0xc42007bb00) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:290 +0x25f 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: created by github.com/tendermint/tendermint/p2p.(*Switch).StopPeerForError 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:256 +0x1b7 ```
7 years ago
p2p: introduce peerConn to simplify peer creation (#1226) * expose AuthEnc in the P2P config if AuthEnc is true, dialed peers must have a node ID in the address and it must match the persistent pubkey from the secret handshake. Refs #1157 * fixes after my own review * fix docs * fix build failure ``` p2p/pex/pex_reactor_test.go:288:88: cannot use seed.NodeInfo().NetAddress() (type *p2p.NetAddress) as type string in array or slice literal ``` * p2p: introduce peerConn to simplify peer creation * Introduce `peerConn` containing the known fields of `peer` * `peer` only created in `sw.addPeer` once handshake is complete and NodeInfo is checked * Eliminates some mutable variables and makes the code flow better * Simplifies the `newXxxPeer` funcs * Use ID instead of PubKey where possible. * SetPubKeyFilter -> SetIDFilter * nodeInfo.Validate takes ID * remove peer.PubKey() * persistent node ids * fixes from review * test: use ip_plus_id.sh more * fix invalid memory panic during fast_sync test ``` 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: panic: runtime error: invalid memory address or nil pointer dereference 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x98dd3e] 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: goroutine 3432 [running]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.newOutboundPeerConn(0xc423fd1380, 0xc420933e00, 0x1, 0x1239a60, 0 xc420128c40, 0x2, 0x42caf6, 0xc42001f300, 0xc422831d98, 0xc4227951c0, ...) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/peer.go:123 +0x31e 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).addOutboundPeerWithConfig(0xc4200ad040, 0xc423fd1380, 0 xc420933e00, 0xc423f48801, 0x28, 0x2) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:455 +0x12b 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).DialPeerWithAddress(0xc4200ad040, 0xc423fd1380, 0x1, 0x 0, 0x0) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:371 +0xdc 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).reconnectToPeer(0xc4200ad040, 0x123e000, 0xc42007bb00) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:290 +0x25f 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: created by github.com/tendermint/tendermint/p2p.(*Switch).StopPeerForError 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:256 +0x1b7 ```
7 years ago
p2p: introduce peerConn to simplify peer creation (#1226) * expose AuthEnc in the P2P config if AuthEnc is true, dialed peers must have a node ID in the address and it must match the persistent pubkey from the secret handshake. Refs #1157 * fixes after my own review * fix docs * fix build failure ``` p2p/pex/pex_reactor_test.go:288:88: cannot use seed.NodeInfo().NetAddress() (type *p2p.NetAddress) as type string in array or slice literal ``` * p2p: introduce peerConn to simplify peer creation * Introduce `peerConn` containing the known fields of `peer` * `peer` only created in `sw.addPeer` once handshake is complete and NodeInfo is checked * Eliminates some mutable variables and makes the code flow better * Simplifies the `newXxxPeer` funcs * Use ID instead of PubKey where possible. * SetPubKeyFilter -> SetIDFilter * nodeInfo.Validate takes ID * remove peer.PubKey() * persistent node ids * fixes from review * test: use ip_plus_id.sh more * fix invalid memory panic during fast_sync test ``` 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: panic: runtime error: invalid memory address or nil pointer dereference 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x98dd3e] 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: goroutine 3432 [running]: 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.newOutboundPeerConn(0xc423fd1380, 0xc420933e00, 0x1, 0x1239a60, 0 xc420128c40, 0x2, 0x42caf6, 0xc42001f300, 0xc422831d98, 0xc4227951c0, ...) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/peer.go:123 +0x31e 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).addOutboundPeerWithConfig(0xc4200ad040, 0xc423fd1380, 0 xc420933e00, 0xc423f48801, 0x28, 0x2) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:455 +0x12b 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).DialPeerWithAddress(0xc4200ad040, 0xc423fd1380, 0x1, 0x 0, 0x0) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:371 +0xdc 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: github.com/tendermint/tendermint/p2p.(*Switch).reconnectToPeer(0xc4200ad040, 0x123e000, 0xc42007bb00) 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:290 +0x25f 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: created by github.com/tendermint/tendermint/p2p.(*Switch).StopPeerForError 2018-02-21T06:30:05Z box887.localdomain docker/local_testnet_4[14907]: #011/go/src/github.com/tendermint/tendermint/p2p/switch.go:256 +0x1b7 ```
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package pex
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/rand"
  6. "reflect"
  7. "sort"
  8. "time"
  9. "github.com/pkg/errors"
  10. wire "github.com/tendermint/go-wire"
  11. cmn "github.com/tendermint/tmlibs/common"
  12. "github.com/tendermint/tendermint/p2p"
  13. "github.com/tendermint/tendermint/p2p/conn"
  14. )
  15. type Peer = p2p.Peer
  16. const (
  17. // PexChannel is a channel for PEX messages
  18. PexChannel = byte(0x00)
  19. maxPexMessageSize = 1048576 // 1MB
  20. // ensure we have enough peers
  21. defaultEnsurePeersPeriod = 30 * time.Second
  22. defaultMinNumOutboundPeers = 10
  23. // Seed/Crawler constants
  24. // TODO:
  25. // We want seeds to only advertise good peers.
  26. // Peers are marked by external mechanisms.
  27. // We need a config value that can be set to be
  28. // on the order of how long it would take before a good
  29. // peer is marked good.
  30. defaultSeedDisconnectWaitPeriod = 2 * time.Minute // disconnect after this
  31. defaultCrawlPeerInterval = 2 * time.Minute // dont redial for this. TODO: back-off
  32. defaultCrawlPeersPeriod = 30 * time.Second // check some peers every this
  33. )
  34. // PEXReactor handles PEX (peer exchange) and ensures that an
  35. // adequate number of peers are connected to the switch.
  36. //
  37. // It uses `AddrBook` (address book) to store `NetAddress`es of the peers.
  38. //
  39. // ## Preventing abuse
  40. //
  41. // Only accept pexAddrsMsg from peers we sent a corresponding pexRequestMsg too.
  42. // Only accept one pexRequestMsg every ~defaultEnsurePeersPeriod.
  43. type PEXReactor struct {
  44. p2p.BaseReactor
  45. book AddrBook
  46. config *PEXReactorConfig
  47. ensurePeersPeriod time.Duration
  48. // maps to prevent abuse
  49. requestsSent *cmn.CMap // ID->struct{}: unanswered send requests
  50. lastReceivedRequests *cmn.CMap // ID->time.Time: last time peer requested from us
  51. }
  52. // PEXReactorConfig holds reactor specific configuration data.
  53. type PEXReactorConfig struct {
  54. // Seed/Crawler mode
  55. SeedMode bool
  56. // Seeds is a list of addresses reactor may use
  57. // if it can't connect to peers in the addrbook.
  58. Seeds []string
  59. }
  60. // NewPEXReactor creates new PEX reactor.
  61. func NewPEXReactor(b AddrBook, config *PEXReactorConfig) *PEXReactor {
  62. r := &PEXReactor{
  63. book: b,
  64. config: config,
  65. ensurePeersPeriod: defaultEnsurePeersPeriod,
  66. requestsSent: cmn.NewCMap(),
  67. lastReceivedRequests: cmn.NewCMap(),
  68. }
  69. r.BaseReactor = *p2p.NewBaseReactor("PEXReactor", r)
  70. return r
  71. }
  72. // OnStart implements BaseService
  73. func (r *PEXReactor) OnStart() error {
  74. if err := r.BaseReactor.OnStart(); err != nil {
  75. return err
  76. }
  77. err := r.book.Start()
  78. if err != nil && err != cmn.ErrAlreadyStarted {
  79. return err
  80. }
  81. // return err if user provided a bad seed address
  82. if err := r.checkSeeds(); err != nil {
  83. return err
  84. }
  85. // Check if this node should run
  86. // in seed/crawler mode
  87. if r.config.SeedMode {
  88. go r.crawlPeersRoutine()
  89. } else {
  90. go r.ensurePeersRoutine()
  91. }
  92. return nil
  93. }
  94. // OnStop implements BaseService
  95. func (r *PEXReactor) OnStop() {
  96. r.BaseReactor.OnStop()
  97. r.book.Stop()
  98. }
  99. // GetChannels implements Reactor
  100. func (r *PEXReactor) GetChannels() []*conn.ChannelDescriptor {
  101. return []*conn.ChannelDescriptor{
  102. {
  103. ID: PexChannel,
  104. Priority: 1,
  105. SendQueueCapacity: 10,
  106. },
  107. }
  108. }
  109. // AddPeer implements Reactor by adding peer to the address book (if inbound)
  110. // or by requesting more addresses (if outbound).
  111. func (r *PEXReactor) AddPeer(p Peer) {
  112. if p.IsOutbound() {
  113. // For outbound peers, the address is already in the books -
  114. // either via DialPeersAsync or r.Receive.
  115. // Ask it for more peers if we need.
  116. if r.book.NeedMoreAddrs() {
  117. r.RequestAddrs(p)
  118. }
  119. } else {
  120. // For inbound peers, the peer is its own source,
  121. // and its NodeInfo has already been validated.
  122. // Let the ensurePeersRoutine handle asking for more
  123. // peers when we need - we don't trust inbound peers as much.
  124. addr := p.NodeInfo().NetAddress()
  125. r.book.AddAddress(addr, addr)
  126. }
  127. }
  128. // RemovePeer implements Reactor.
  129. func (r *PEXReactor) RemovePeer(p Peer, reason interface{}) {
  130. id := string(p.ID())
  131. r.requestsSent.Delete(id)
  132. r.lastReceivedRequests.Delete(id)
  133. }
  134. // Receive implements Reactor by handling incoming PEX messages.
  135. func (r *PEXReactor) Receive(chID byte, src Peer, msgBytes []byte) {
  136. _, msg, err := DecodeMessage(msgBytes)
  137. if err != nil {
  138. r.Logger.Error("Error decoding message", "err", err)
  139. return
  140. }
  141. r.Logger.Debug("Received message", "src", src, "chId", chID, "msg", msg)
  142. switch msg := msg.(type) {
  143. case *pexRequestMessage:
  144. // Check we're not receiving too many requests
  145. if err := r.receiveRequest(src); err != nil {
  146. r.Switch.StopPeerForError(src, err)
  147. return
  148. }
  149. // Seeds disconnect after sending a batch of addrs
  150. if r.config.SeedMode {
  151. // TODO: should we be more selective ?
  152. r.SendAddrs(src, r.book.GetSelection())
  153. r.Switch.StopPeerGracefully(src)
  154. } else {
  155. r.SendAddrs(src, r.book.GetSelection())
  156. }
  157. case *pexAddrsMessage:
  158. // If we asked for addresses, add them to the book
  159. if err := r.ReceiveAddrs(msg.Addrs, src); err != nil {
  160. r.Switch.StopPeerForError(src, err)
  161. return
  162. }
  163. default:
  164. r.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg)))
  165. }
  166. }
  167. func (r *PEXReactor) receiveRequest(src Peer) error {
  168. id := string(src.ID())
  169. v := r.lastReceivedRequests.Get(id)
  170. if v == nil {
  171. // initialize with empty time
  172. lastReceived := time.Time{}
  173. r.lastReceivedRequests.Set(id, lastReceived)
  174. return nil
  175. }
  176. lastReceived := v.(time.Time)
  177. if lastReceived.Equal(time.Time{}) {
  178. // first time gets a free pass. then we start tracking the time
  179. lastReceived = time.Now()
  180. r.lastReceivedRequests.Set(id, lastReceived)
  181. return nil
  182. }
  183. now := time.Now()
  184. if now.Sub(lastReceived) < r.ensurePeersPeriod/3 {
  185. return fmt.Errorf("Peer (%v) is sending too many PEX requests. Disconnecting", src.ID())
  186. }
  187. r.lastReceivedRequests.Set(id, now)
  188. return nil
  189. }
  190. // RequestAddrs asks peer for more addresses if we do not already
  191. // have a request out for this peer.
  192. func (r *PEXReactor) RequestAddrs(p Peer) {
  193. id := string(p.ID())
  194. if r.requestsSent.Has(id) {
  195. return
  196. }
  197. r.requestsSent.Set(id, struct{}{})
  198. p.Send(PexChannel, struct{ PexMessage }{&pexRequestMessage{}})
  199. }
  200. // ReceiveAddrs adds the given addrs to the addrbook if theres an open
  201. // request for this peer and deletes the open request.
  202. // If there's no open request for the src peer, it returns an error.
  203. func (r *PEXReactor) ReceiveAddrs(addrs []*p2p.NetAddress, src Peer) error {
  204. id := string(src.ID())
  205. if !r.requestsSent.Has(id) {
  206. return errors.New("Received unsolicited pexAddrsMessage")
  207. }
  208. r.requestsSent.Delete(id)
  209. srcAddr := src.NodeInfo().NetAddress()
  210. for _, netAddr := range addrs {
  211. if netAddr != nil {
  212. r.book.AddAddress(netAddr, srcAddr)
  213. }
  214. }
  215. return nil
  216. }
  217. // SendAddrs sends addrs to the peer.
  218. func (r *PEXReactor) SendAddrs(p Peer, netAddrs []*p2p.NetAddress) {
  219. p.Send(PexChannel, struct{ PexMessage }{&pexAddrsMessage{Addrs: netAddrs}})
  220. }
  221. // SetEnsurePeersPeriod sets period to ensure peers connected.
  222. func (r *PEXReactor) SetEnsurePeersPeriod(d time.Duration) {
  223. r.ensurePeersPeriod = d
  224. }
  225. // Ensures that sufficient peers are connected. (continuous)
  226. func (r *PEXReactor) ensurePeersRoutine() {
  227. var (
  228. seed = rand.New(rand.NewSource(time.Now().UnixNano()))
  229. jitter = seed.Int63n(r.ensurePeersPeriod.Nanoseconds())
  230. )
  231. // Randomize first round of communication to avoid thundering herd.
  232. // If no potential peers are present directly start connecting so we guarantee
  233. // swift setup with the help of configured seeds.
  234. if r.hasPotentialPeers() {
  235. time.Sleep(time.Duration(jitter))
  236. }
  237. // fire once immediately.
  238. // ensures we dial the seeds right away if the book is empty
  239. r.ensurePeers()
  240. // fire periodically
  241. ticker := time.NewTicker(r.ensurePeersPeriod)
  242. for {
  243. select {
  244. case <-ticker.C:
  245. r.ensurePeers()
  246. case <-r.Quit():
  247. ticker.Stop()
  248. return
  249. }
  250. }
  251. }
  252. // ensurePeers ensures that sufficient peers are connected. (once)
  253. //
  254. // heuristic that we haven't perfected yet, or, perhaps is manually edited by
  255. // the node operator. It should not be used to compute what addresses are
  256. // already connected or not.
  257. func (r *PEXReactor) ensurePeers() {
  258. var (
  259. out, in, dial = r.Switch.NumPeers()
  260. numToDial = defaultMinNumOutboundPeers - (out + dial)
  261. )
  262. r.Logger.Info(
  263. "Ensure peers",
  264. "numOutPeers", out,
  265. "numInPeers", in,
  266. "numDialing", dial,
  267. "numToDial", numToDial,
  268. )
  269. if numToDial <= 0 {
  270. return
  271. }
  272. // bias to prefer more vetted peers when we have fewer connections.
  273. // not perfect, but somewhate ensures that we prioritize connecting to more-vetted
  274. // NOTE: range here is [10, 90]. Too high ?
  275. newBias := cmn.MinInt(out, 8)*10 + 10
  276. toDial := make(map[p2p.ID]*p2p.NetAddress)
  277. // Try maxAttempts times to pick numToDial addresses to dial
  278. maxAttempts := numToDial * 3
  279. for i := 0; i < maxAttempts && len(toDial) < numToDial; i++ {
  280. try := r.book.PickAddress(newBias)
  281. if try == nil {
  282. continue
  283. }
  284. if _, selected := toDial[try.ID]; selected {
  285. continue
  286. }
  287. if dialling := r.Switch.IsDialing(try.ID); dialling {
  288. continue
  289. }
  290. if connected := r.Switch.Peers().Has(try.ID); connected {
  291. continue
  292. }
  293. r.Logger.Info("Will dial address", "addr", try)
  294. toDial[try.ID] = try
  295. }
  296. // Dial picked addresses
  297. for _, item := range toDial {
  298. go func(picked *p2p.NetAddress) {
  299. err := r.Switch.DialPeerWithAddress(picked, false)
  300. if err != nil {
  301. r.Logger.Error("Dialing failed", "err", err)
  302. // TODO: detect more "bad peer" scenarios
  303. if _, ok := err.(p2p.ErrSwitchAuthenticationFailure); ok {
  304. r.book.MarkBad(picked)
  305. } else {
  306. r.book.MarkAttempt(picked)
  307. }
  308. }
  309. }(item)
  310. }
  311. // If we need more addresses, pick a random peer and ask for more.
  312. if r.book.NeedMoreAddrs() {
  313. peers := r.Switch.Peers().List()
  314. peersCount := len(peers)
  315. if peersCount > 0 {
  316. peer := peers[rand.Int()%peersCount] // nolint: gas
  317. r.Logger.Info("We need more addresses. Sending pexRequest to random peer", "peer", peer)
  318. r.RequestAddrs(peer)
  319. }
  320. }
  321. // If we are not connected to nor dialing anybody, fallback to dialing a seed.
  322. if out+in+dial+len(toDial) == 0 {
  323. r.Logger.Info("No addresses to dial nor connected peers. Falling back to seeds")
  324. r.dialSeeds()
  325. }
  326. }
  327. // check seed addresses are well formed
  328. func (r *PEXReactor) checkSeeds() error {
  329. lSeeds := len(r.config.Seeds)
  330. if lSeeds == 0 {
  331. return nil
  332. }
  333. _, errs := p2p.NewNetAddressStrings(r.config.Seeds)
  334. for _, err := range errs {
  335. if err != nil {
  336. return err
  337. }
  338. }
  339. return nil
  340. }
  341. // randomly dial seeds until we connect to one or exhaust them
  342. func (r *PEXReactor) dialSeeds() {
  343. lSeeds := len(r.config.Seeds)
  344. if lSeeds == 0 {
  345. return
  346. }
  347. seedAddrs, _ := p2p.NewNetAddressStrings(r.config.Seeds)
  348. perm := rand.Perm(lSeeds)
  349. // perm := r.Switch.rng.Perm(lSeeds)
  350. for _, i := range perm {
  351. // dial a random seed
  352. seedAddr := seedAddrs[i]
  353. err := r.Switch.DialPeerWithAddress(seedAddr, false)
  354. if err == nil {
  355. return
  356. }
  357. r.Switch.Logger.Error("Error dialing seed", "err", err, "seed", seedAddr)
  358. }
  359. r.Switch.Logger.Error("Couldn't connect to any seeds")
  360. }
  361. //----------------------------------------------------------
  362. // Explores the network searching for more peers. (continuous)
  363. // Seed/Crawler Mode causes this node to quickly disconnect
  364. // from peers, except other seed nodes.
  365. func (r *PEXReactor) crawlPeersRoutine() {
  366. // Do an initial crawl
  367. r.crawlPeers()
  368. // Fire periodically
  369. ticker := time.NewTicker(defaultCrawlPeersPeriod)
  370. for {
  371. select {
  372. case <-ticker.C:
  373. r.attemptDisconnects()
  374. r.crawlPeers()
  375. case <-r.Quit():
  376. return
  377. }
  378. }
  379. }
  380. // hasPotentialPeers indicates if there is a potential peer to connect to, by
  381. // consulting the Switch as well as the AddrBook.
  382. func (r *PEXReactor) hasPotentialPeers() bool {
  383. out, in, dial := r.Switch.NumPeers()
  384. return out+in+dial > 0 && len(r.book.ListOfKnownAddresses()) > 0
  385. }
  386. // crawlPeerInfo handles temporary data needed for the
  387. // network crawling performed during seed/crawler mode.
  388. type crawlPeerInfo struct {
  389. // The listening address of a potential peer we learned about
  390. Addr *p2p.NetAddress
  391. // The last time we attempt to reach this address
  392. LastAttempt time.Time
  393. // The last time we successfully reached this address
  394. LastSuccess time.Time
  395. }
  396. // oldestFirst implements sort.Interface for []crawlPeerInfo
  397. // based on the LastAttempt field.
  398. type oldestFirst []crawlPeerInfo
  399. func (of oldestFirst) Len() int { return len(of) }
  400. func (of oldestFirst) Swap(i, j int) { of[i], of[j] = of[j], of[i] }
  401. func (of oldestFirst) Less(i, j int) bool { return of[i].LastAttempt.Before(of[j].LastAttempt) }
  402. // getPeersToCrawl returns addresses of potential peers that we wish to validate.
  403. // NOTE: The status information is ordered as described above.
  404. func (r *PEXReactor) getPeersToCrawl() []crawlPeerInfo {
  405. var of oldestFirst
  406. // TODO: be more selective
  407. addrs := r.book.ListOfKnownAddresses()
  408. for _, addr := range addrs {
  409. if len(addr.ID()) == 0 {
  410. continue // dont use peers without id
  411. }
  412. of = append(of, crawlPeerInfo{
  413. Addr: addr.Addr,
  414. LastAttempt: addr.LastAttempt,
  415. LastSuccess: addr.LastSuccess,
  416. })
  417. }
  418. sort.Sort(of)
  419. return of
  420. }
  421. // crawlPeers will crawl the network looking for new peer addresses. (once)
  422. func (r *PEXReactor) crawlPeers() {
  423. peerInfos := r.getPeersToCrawl()
  424. now := time.Now()
  425. // Use addresses we know of to reach additional peers
  426. for _, pi := range peerInfos {
  427. // Do not attempt to connect with peers we recently dialed
  428. if now.Sub(pi.LastAttempt) < defaultCrawlPeerInterval {
  429. continue
  430. }
  431. // Otherwise, attempt to connect with the known address
  432. err := r.Switch.DialPeerWithAddress(pi.Addr, false)
  433. if err != nil {
  434. r.book.MarkAttempt(pi.Addr)
  435. continue
  436. }
  437. }
  438. // Crawl the connected peers asking for more addresses
  439. for _, pi := range peerInfos {
  440. // We will wait a minimum period of time before crawling peers again
  441. if now.Sub(pi.LastAttempt) >= defaultCrawlPeerInterval {
  442. peer := r.Switch.Peers().Get(pi.Addr.ID)
  443. if peer != nil {
  444. r.RequestAddrs(peer)
  445. }
  446. }
  447. }
  448. }
  449. // attemptDisconnects checks if we've been with each peer long enough to disconnect
  450. func (r *PEXReactor) attemptDisconnects() {
  451. for _, peer := range r.Switch.Peers().List() {
  452. status := peer.Status()
  453. if status.Duration < defaultSeedDisconnectWaitPeriod {
  454. continue
  455. }
  456. if peer.IsPersistent() {
  457. continue
  458. }
  459. r.Switch.StopPeerGracefully(peer)
  460. }
  461. }
  462. //-----------------------------------------------------------------------------
  463. // Messages
  464. const (
  465. msgTypeRequest = byte(0x01)
  466. msgTypeAddrs = byte(0x02)
  467. )
  468. // PexMessage is a primary type for PEX messages. Underneath, it could contain
  469. // either pexRequestMessage, or pexAddrsMessage messages.
  470. type PexMessage interface{}
  471. var _ = wire.RegisterInterface(
  472. struct{ PexMessage }{},
  473. wire.ConcreteType{&pexRequestMessage{}, msgTypeRequest},
  474. wire.ConcreteType{&pexAddrsMessage{}, msgTypeAddrs},
  475. )
  476. // DecodeMessage implements interface registered above.
  477. func DecodeMessage(bz []byte) (msgType byte, msg PexMessage, err error) {
  478. msgType = bz[0]
  479. n := new(int)
  480. r := bytes.NewReader(bz)
  481. msg = wire.ReadBinary(struct{ PexMessage }{}, r, maxPexMessageSize, n, &err).(struct{ PexMessage }).PexMessage
  482. return
  483. }
  484. /*
  485. A pexRequestMessage requests additional peer addresses.
  486. */
  487. type pexRequestMessage struct {
  488. }
  489. func (m *pexRequestMessage) String() string {
  490. return "[pexRequest]"
  491. }
  492. /*
  493. A message with announced peer addresses.
  494. */
  495. type pexAddrsMessage struct {
  496. Addrs []*p2p.NetAddress
  497. }
  498. func (m *pexAddrsMessage) String() string {
  499. return fmt.Sprintf("[pexAddrs %v]", m.Addrs)
  500. }