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.

550 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
9 years ago
8 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. // Randomize when routine starts
  228. ensurePeersPeriodMs := r.ensurePeersPeriod.Nanoseconds() / 1e6
  229. time.Sleep(time.Duration(rand.Int63n(ensurePeersPeriodMs)) * time.Millisecond)
  230. // fire once immediately.
  231. // ensures we dial the seeds right away if the book is empty
  232. r.ensurePeers()
  233. // fire periodically
  234. ticker := time.NewTicker(r.ensurePeersPeriod)
  235. for {
  236. select {
  237. case <-ticker.C:
  238. r.ensurePeers()
  239. case <-r.Quit():
  240. ticker.Stop()
  241. return
  242. }
  243. }
  244. }
  245. // ensurePeers ensures that sufficient peers are connected. (once)
  246. //
  247. // heuristic that we haven't perfected yet, or, perhaps is manually edited by
  248. // the node operator. It should not be used to compute what addresses are
  249. // already connected or not.
  250. func (r *PEXReactor) ensurePeers() {
  251. numOutPeers, numInPeers, numDialing := r.Switch.NumPeers()
  252. numToDial := defaultMinNumOutboundPeers - (numOutPeers + numDialing)
  253. r.Logger.Info("Ensure peers", "numOutPeers", numOutPeers, "numDialing", numDialing, "numToDial", numToDial)
  254. if numToDial <= 0 {
  255. return
  256. }
  257. // bias to prefer more vetted peers when we have fewer connections.
  258. // not perfect, but somewhate ensures that we prioritize connecting to more-vetted
  259. // NOTE: range here is [10, 90]. Too high ?
  260. newBias := cmn.MinInt(numOutPeers, 8)*10 + 10
  261. toDial := make(map[p2p.ID]*p2p.NetAddress)
  262. // Try maxAttempts times to pick numToDial addresses to dial
  263. maxAttempts := numToDial * 3
  264. for i := 0; i < maxAttempts && len(toDial) < numToDial; i++ {
  265. try := r.book.PickAddress(newBias)
  266. if try == nil {
  267. continue
  268. }
  269. if _, selected := toDial[try.ID]; selected {
  270. continue
  271. }
  272. if dialling := r.Switch.IsDialing(try.ID); dialling {
  273. continue
  274. }
  275. if connected := r.Switch.Peers().Has(try.ID); connected {
  276. continue
  277. }
  278. r.Logger.Info("Will dial address", "addr", try)
  279. toDial[try.ID] = try
  280. }
  281. // Dial picked addresses
  282. for _, item := range toDial {
  283. go func(picked *p2p.NetAddress) {
  284. err := r.Switch.DialPeerWithAddress(picked, false)
  285. if err != nil {
  286. r.Logger.Error("Dialing failed", "err", err)
  287. // TODO: detect more "bad peer" scenarios
  288. if _, ok := err.(p2p.ErrSwitchAuthenticationFailure); ok {
  289. r.book.MarkBad(picked)
  290. } else {
  291. r.book.MarkAttempt(picked)
  292. }
  293. }
  294. }(item)
  295. }
  296. // If we need more addresses, pick a random peer and ask for more.
  297. if r.book.NeedMoreAddrs() {
  298. peers := r.Switch.Peers().List()
  299. peersCount := len(peers)
  300. if peersCount > 0 {
  301. peer := peers[rand.Int()%peersCount] // nolint: gas
  302. r.Logger.Info("We need more addresses. Sending pexRequest to random peer", "peer", peer)
  303. r.RequestAddrs(peer)
  304. }
  305. }
  306. // If we are not connected to nor dialing anybody, fallback to dialing a seed.
  307. if numOutPeers+numInPeers+numDialing+len(toDial) == 0 {
  308. r.Logger.Info("No addresses to dial nor connected peers. Falling back to seeds")
  309. r.dialSeeds()
  310. }
  311. }
  312. // check seed addresses are well formed
  313. func (r *PEXReactor) checkSeeds() error {
  314. lSeeds := len(r.config.Seeds)
  315. if lSeeds == 0 {
  316. return nil
  317. }
  318. _, errs := p2p.NewNetAddressStrings(r.config.Seeds)
  319. for _, err := range errs {
  320. if err != nil {
  321. return err
  322. }
  323. }
  324. return nil
  325. }
  326. // randomly dial seeds until we connect to one or exhaust them
  327. func (r *PEXReactor) dialSeeds() {
  328. lSeeds := len(r.config.Seeds)
  329. if lSeeds == 0 {
  330. return
  331. }
  332. seedAddrs, _ := p2p.NewNetAddressStrings(r.config.Seeds)
  333. perm := rand.Perm(lSeeds)
  334. // perm := r.Switch.rng.Perm(lSeeds)
  335. for _, i := range perm {
  336. // dial a random seed
  337. seedAddr := seedAddrs[i]
  338. err := r.Switch.DialPeerWithAddress(seedAddr, false)
  339. if err == nil {
  340. return
  341. }
  342. r.Switch.Logger.Error("Error dialing seed", "err", err, "seed", seedAddr)
  343. }
  344. r.Switch.Logger.Error("Couldn't connect to any seeds")
  345. }
  346. //----------------------------------------------------------
  347. // Explores the network searching for more peers. (continuous)
  348. // Seed/Crawler Mode causes this node to quickly disconnect
  349. // from peers, except other seed nodes.
  350. func (r *PEXReactor) crawlPeersRoutine() {
  351. // Do an initial crawl
  352. r.crawlPeers()
  353. // Fire periodically
  354. ticker := time.NewTicker(defaultCrawlPeersPeriod)
  355. for {
  356. select {
  357. case <-ticker.C:
  358. r.attemptDisconnects()
  359. r.crawlPeers()
  360. case <-r.Quit():
  361. return
  362. }
  363. }
  364. }
  365. // crawlPeerInfo handles temporary data needed for the
  366. // network crawling performed during seed/crawler mode.
  367. type crawlPeerInfo struct {
  368. // The listening address of a potential peer we learned about
  369. Addr *p2p.NetAddress
  370. // The last time we attempt to reach this address
  371. LastAttempt time.Time
  372. // The last time we successfully reached this address
  373. LastSuccess time.Time
  374. }
  375. // oldestFirst implements sort.Interface for []crawlPeerInfo
  376. // based on the LastAttempt field.
  377. type oldestFirst []crawlPeerInfo
  378. func (of oldestFirst) Len() int { return len(of) }
  379. func (of oldestFirst) Swap(i, j int) { of[i], of[j] = of[j], of[i] }
  380. func (of oldestFirst) Less(i, j int) bool { return of[i].LastAttempt.Before(of[j].LastAttempt) }
  381. // getPeersToCrawl returns addresses of potential peers that we wish to validate.
  382. // NOTE: The status information is ordered as described above.
  383. func (r *PEXReactor) getPeersToCrawl() []crawlPeerInfo {
  384. var of oldestFirst
  385. // TODO: be more selective
  386. addrs := r.book.ListOfKnownAddresses()
  387. for _, addr := range addrs {
  388. if len(addr.ID()) == 0 {
  389. continue // dont use peers without id
  390. }
  391. of = append(of, crawlPeerInfo{
  392. Addr: addr.Addr,
  393. LastAttempt: addr.LastAttempt,
  394. LastSuccess: addr.LastSuccess,
  395. })
  396. }
  397. sort.Sort(of)
  398. return of
  399. }
  400. // crawlPeers will crawl the network looking for new peer addresses. (once)
  401. func (r *PEXReactor) crawlPeers() {
  402. peerInfos := r.getPeersToCrawl()
  403. now := time.Now()
  404. // Use addresses we know of to reach additional peers
  405. for _, pi := range peerInfos {
  406. // Do not attempt to connect with peers we recently dialed
  407. if now.Sub(pi.LastAttempt) < defaultCrawlPeerInterval {
  408. continue
  409. }
  410. // Otherwise, attempt to connect with the known address
  411. err := r.Switch.DialPeerWithAddress(pi.Addr, false)
  412. if err != nil {
  413. r.book.MarkAttempt(pi.Addr)
  414. continue
  415. }
  416. }
  417. // Crawl the connected peers asking for more addresses
  418. for _, pi := range peerInfos {
  419. // We will wait a minimum period of time before crawling peers again
  420. if now.Sub(pi.LastAttempt) >= defaultCrawlPeerInterval {
  421. peer := r.Switch.Peers().Get(pi.Addr.ID)
  422. if peer != nil {
  423. r.RequestAddrs(peer)
  424. }
  425. }
  426. }
  427. }
  428. // attemptDisconnects checks if we've been with each peer long enough to disconnect
  429. func (r *PEXReactor) attemptDisconnects() {
  430. for _, peer := range r.Switch.Peers().List() {
  431. status := peer.Status()
  432. if status.Duration < defaultSeedDisconnectWaitPeriod {
  433. continue
  434. }
  435. if peer.IsPersistent() {
  436. continue
  437. }
  438. r.Switch.StopPeerGracefully(peer)
  439. }
  440. }
  441. //-----------------------------------------------------------------------------
  442. // Messages
  443. const (
  444. msgTypeRequest = byte(0x01)
  445. msgTypeAddrs = byte(0x02)
  446. )
  447. // PexMessage is a primary type for PEX messages. Underneath, it could contain
  448. // either pexRequestMessage, or pexAddrsMessage messages.
  449. type PexMessage interface{}
  450. var _ = wire.RegisterInterface(
  451. struct{ PexMessage }{},
  452. wire.ConcreteType{&pexRequestMessage{}, msgTypeRequest},
  453. wire.ConcreteType{&pexAddrsMessage{}, msgTypeAddrs},
  454. )
  455. // DecodeMessage implements interface registered above.
  456. func DecodeMessage(bz []byte) (msgType byte, msg PexMessage, err error) {
  457. msgType = bz[0]
  458. n := new(int)
  459. r := bytes.NewReader(bz)
  460. msg = wire.ReadBinary(struct{ PexMessage }{}, r, maxPexMessageSize, n, &err).(struct{ PexMessage }).PexMessage
  461. return
  462. }
  463. /*
  464. A pexRequestMessage requests additional peer addresses.
  465. */
  466. type pexRequestMessage struct {
  467. }
  468. func (m *pexRequestMessage) String() string {
  469. return "[pexRequest]"
  470. }
  471. /*
  472. A message with announced peer addresses.
  473. */
  474. type pexAddrsMessage struct {
  475. Addrs []*p2p.NetAddress
  476. }
  477. func (m *pexAddrsMessage) String() string {
  478. return fmt.Sprintf("[pexAddrs %v]", m.Addrs)
  479. }