peer.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. // Contains the active peer-set of the downloader, maintaining both failures
  17. // as well as reputation metrics to prioritize the block retrievals.
  18. package downloader
  19. import (
  20. "errors"
  21. "math/big"
  22. "sort"
  23. "sync"
  24. "sync/atomic"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/eth/protocols/eth"
  28. "github.com/ethereum/go-ethereum/event"
  29. "github.com/ethereum/go-ethereum/log"
  30. "github.com/ethereum/go-ethereum/p2p/msgrate"
  31. )
  32. const (
  33. maxLackingHashes = 4096 // Maximum number of entries allowed on the list or lacking items
  34. )
  35. var (
  36. errAlreadyFetching = errors.New("already fetching blocks from peer")
  37. errAlreadyRegistered = errors.New("peer is already registered")
  38. errNotRegistered = errors.New("peer is not registered")
  39. )
  40. // peerConnection represents an active peer from which hashes and blocks are retrieved.
  41. type peerConnection struct {
  42. id string // Unique identifier of the peer
  43. headerIdle int32 // Current header activity state of the peer (idle = 0, active = 1)
  44. blockIdle int32 // Current block activity state of the peer (idle = 0, active = 1)
  45. receiptIdle int32 // Current receipt activity state of the peer (idle = 0, active = 1)
  46. stateIdle int32 // Current node data activity state of the peer (idle = 0, active = 1)
  47. headerStarted time.Time // Time instance when the last header fetch was started
  48. blockStarted time.Time // Time instance when the last block (body) fetch was started
  49. receiptStarted time.Time // Time instance when the last receipt fetch was started
  50. stateStarted time.Time // Time instance when the last node data fetch was started
  51. rates *msgrate.Tracker // Tracker to hone in on the number of items retrievable per second
  52. lacking map[common.Hash]struct{} // Set of hashes not to request (didn't have previously)
  53. peer Peer
  54. version uint // Eth protocol version number to switch strategies
  55. log log.Logger // Contextual logger to add extra infos to peer logs
  56. lock sync.RWMutex
  57. }
  58. // LightPeer encapsulates the methods required to synchronise with a remote light peer.
  59. type LightPeer interface {
  60. Head() (common.Hash, *big.Int)
  61. RequestHeadersByHash(common.Hash, int, int, bool) error
  62. RequestHeadersByNumber(uint64, int, int, bool) error
  63. }
  64. // Peer encapsulates the methods required to synchronise with a remote full peer.
  65. type Peer interface {
  66. LightPeer
  67. RequestBodies([]common.Hash) error
  68. RequestReceipts([]common.Hash) error
  69. RequestNodeData([]common.Hash) error
  70. }
  71. // lightPeerWrapper wraps a LightPeer struct, stubbing out the Peer-only methods.
  72. type lightPeerWrapper struct {
  73. peer LightPeer
  74. }
  75. func (w *lightPeerWrapper) Head() (common.Hash, *big.Int) { return w.peer.Head() }
  76. func (w *lightPeerWrapper) RequestHeadersByHash(h common.Hash, amount int, skip int, reverse bool) error {
  77. return w.peer.RequestHeadersByHash(h, amount, skip, reverse)
  78. }
  79. func (w *lightPeerWrapper) RequestHeadersByNumber(i uint64, amount int, skip int, reverse bool) error {
  80. return w.peer.RequestHeadersByNumber(i, amount, skip, reverse)
  81. }
  82. func (w *lightPeerWrapper) RequestBodies([]common.Hash) error {
  83. panic("RequestBodies not supported in light client mode sync")
  84. }
  85. func (w *lightPeerWrapper) RequestReceipts([]common.Hash) error {
  86. panic("RequestReceipts not supported in light client mode sync")
  87. }
  88. func (w *lightPeerWrapper) RequestNodeData([]common.Hash) error {
  89. panic("RequestNodeData not supported in light client mode sync")
  90. }
  91. // newPeerConnection creates a new downloader peer.
  92. func newPeerConnection(id string, version uint, peer Peer, logger log.Logger) *peerConnection {
  93. return &peerConnection{
  94. id: id,
  95. lacking: make(map[common.Hash]struct{}),
  96. peer: peer,
  97. version: version,
  98. log: logger,
  99. }
  100. }
  101. // Reset clears the internal state of a peer entity.
  102. func (p *peerConnection) Reset() {
  103. p.lock.Lock()
  104. defer p.lock.Unlock()
  105. atomic.StoreInt32(&p.headerIdle, 0)
  106. atomic.StoreInt32(&p.blockIdle, 0)
  107. atomic.StoreInt32(&p.receiptIdle, 0)
  108. atomic.StoreInt32(&p.stateIdle, 0)
  109. p.lacking = make(map[common.Hash]struct{})
  110. }
  111. // FetchHeaders sends a header retrieval request to the remote peer.
  112. func (p *peerConnection) FetchHeaders(from uint64, count int) error {
  113. // Short circuit if the peer is already fetching
  114. if !atomic.CompareAndSwapInt32(&p.headerIdle, 0, 1) {
  115. return errAlreadyFetching
  116. }
  117. p.headerStarted = time.Now()
  118. // Issue the header retrieval request (absolute upwards without gaps)
  119. go p.peer.RequestHeadersByNumber(from, count, 0, false)
  120. return nil
  121. }
  122. // FetchBodies sends a block body retrieval request to the remote peer.
  123. func (p *peerConnection) FetchBodies(request *fetchRequest) error {
  124. // Short circuit if the peer is already fetching
  125. if !atomic.CompareAndSwapInt32(&p.blockIdle, 0, 1) {
  126. return errAlreadyFetching
  127. }
  128. p.blockStarted = time.Now()
  129. go func() {
  130. // Convert the header set to a retrievable slice
  131. hashes := make([]common.Hash, 0, len(request.Headers))
  132. for _, header := range request.Headers {
  133. hashes = append(hashes, header.Hash())
  134. }
  135. p.peer.RequestBodies(hashes)
  136. }()
  137. return nil
  138. }
  139. // FetchReceipts sends a receipt retrieval request to the remote peer.
  140. func (p *peerConnection) FetchReceipts(request *fetchRequest) error {
  141. // Short circuit if the peer is already fetching
  142. if !atomic.CompareAndSwapInt32(&p.receiptIdle, 0, 1) {
  143. return errAlreadyFetching
  144. }
  145. p.receiptStarted = time.Now()
  146. go func() {
  147. // Convert the header set to a retrievable slice
  148. hashes := make([]common.Hash, 0, len(request.Headers))
  149. for _, header := range request.Headers {
  150. hashes = append(hashes, header.Hash())
  151. }
  152. p.peer.RequestReceipts(hashes)
  153. }()
  154. return nil
  155. }
  156. // FetchNodeData sends a node state data retrieval request to the remote peer.
  157. func (p *peerConnection) FetchNodeData(hashes []common.Hash) error {
  158. // Short circuit if the peer is already fetching
  159. if !atomic.CompareAndSwapInt32(&p.stateIdle, 0, 1) {
  160. return errAlreadyFetching
  161. }
  162. p.stateStarted = time.Now()
  163. go p.peer.RequestNodeData(hashes)
  164. return nil
  165. }
  166. // SetHeadersIdle sets the peer to idle, allowing it to execute new header retrieval
  167. // requests. Its estimated header retrieval throughput is updated with that measured
  168. // just now.
  169. func (p *peerConnection) SetHeadersIdle(delivered int, deliveryTime time.Time) {
  170. p.rates.Update(eth.BlockHeadersMsg, deliveryTime.Sub(p.headerStarted), delivered)
  171. atomic.StoreInt32(&p.headerIdle, 0)
  172. }
  173. // SetBodiesIdle sets the peer to idle, allowing it to execute block body retrieval
  174. // requests. Its estimated body retrieval throughput is updated with that measured
  175. // just now.
  176. func (p *peerConnection) SetBodiesIdle(delivered int, deliveryTime time.Time) {
  177. p.rates.Update(eth.BlockBodiesMsg, deliveryTime.Sub(p.blockStarted), delivered)
  178. atomic.StoreInt32(&p.blockIdle, 0)
  179. }
  180. // SetReceiptsIdle sets the peer to idle, allowing it to execute new receipt
  181. // retrieval requests. Its estimated receipt retrieval throughput is updated
  182. // with that measured just now.
  183. func (p *peerConnection) SetReceiptsIdle(delivered int, deliveryTime time.Time) {
  184. p.rates.Update(eth.ReceiptsMsg, deliveryTime.Sub(p.receiptStarted), delivered)
  185. atomic.StoreInt32(&p.receiptIdle, 0)
  186. }
  187. // SetNodeDataIdle sets the peer to idle, allowing it to execute new state trie
  188. // data retrieval requests. Its estimated state retrieval throughput is updated
  189. // with that measured just now.
  190. func (p *peerConnection) SetNodeDataIdle(delivered int, deliveryTime time.Time) {
  191. p.rates.Update(eth.NodeDataMsg, deliveryTime.Sub(p.stateStarted), delivered)
  192. atomic.StoreInt32(&p.stateIdle, 0)
  193. }
  194. // HeaderCapacity retrieves the peers header download allowance based on its
  195. // previously discovered throughput.
  196. func (p *peerConnection) HeaderCapacity(targetRTT time.Duration) int {
  197. cap := p.rates.Capacity(eth.BlockHeadersMsg, targetRTT)
  198. if cap > MaxHeaderFetch {
  199. cap = MaxHeaderFetch
  200. }
  201. return cap
  202. }
  203. // BlockCapacity retrieves the peers block download allowance based on its
  204. // previously discovered throughput.
  205. func (p *peerConnection) BlockCapacity(targetRTT time.Duration) int {
  206. cap := p.rates.Capacity(eth.BlockBodiesMsg, targetRTT)
  207. if cap > MaxBlockFetch {
  208. cap = MaxBlockFetch
  209. }
  210. return cap
  211. }
  212. // ReceiptCapacity retrieves the peers receipt download allowance based on its
  213. // previously discovered throughput.
  214. func (p *peerConnection) ReceiptCapacity(targetRTT time.Duration) int {
  215. cap := p.rates.Capacity(eth.ReceiptsMsg, targetRTT)
  216. if cap > MaxReceiptFetch {
  217. cap = MaxReceiptFetch
  218. }
  219. return cap
  220. }
  221. // NodeDataCapacity retrieves the peers state download allowance based on its
  222. // previously discovered throughput.
  223. func (p *peerConnection) NodeDataCapacity(targetRTT time.Duration) int {
  224. cap := p.rates.Capacity(eth.NodeDataMsg, targetRTT)
  225. if cap > MaxStateFetch {
  226. cap = MaxStateFetch
  227. }
  228. return cap
  229. }
  230. // MarkLacking appends a new entity to the set of items (blocks, receipts, states)
  231. // that a peer is known not to have (i.e. have been requested before). If the
  232. // set reaches its maximum allowed capacity, items are randomly dropped off.
  233. func (p *peerConnection) MarkLacking(hash common.Hash) {
  234. p.lock.Lock()
  235. defer p.lock.Unlock()
  236. for len(p.lacking) >= maxLackingHashes {
  237. for drop := range p.lacking {
  238. delete(p.lacking, drop)
  239. break
  240. }
  241. }
  242. p.lacking[hash] = struct{}{}
  243. }
  244. // Lacks retrieves whether the hash of a blockchain item is on the peers lacking
  245. // list (i.e. whether we know that the peer does not have it).
  246. func (p *peerConnection) Lacks(hash common.Hash) bool {
  247. p.lock.RLock()
  248. defer p.lock.RUnlock()
  249. _, ok := p.lacking[hash]
  250. return ok
  251. }
  252. // peerSet represents the collection of active peer participating in the chain
  253. // download procedure.
  254. type peerSet struct {
  255. peers map[string]*peerConnection
  256. rates *msgrate.Trackers // Set of rate trackers to give the sync a common beat
  257. newPeerFeed event.Feed
  258. peerDropFeed event.Feed
  259. lock sync.RWMutex
  260. }
  261. // newPeerSet creates a new peer set top track the active download sources.
  262. func newPeerSet() *peerSet {
  263. return &peerSet{
  264. peers: make(map[string]*peerConnection),
  265. rates: msgrate.NewTrackers(log.New("proto", "eth")),
  266. }
  267. }
  268. // SubscribeNewPeers subscribes to peer arrival events.
  269. func (ps *peerSet) SubscribeNewPeers(ch chan<- *peerConnection) event.Subscription {
  270. return ps.newPeerFeed.Subscribe(ch)
  271. }
  272. // SubscribePeerDrops subscribes to peer departure events.
  273. func (ps *peerSet) SubscribePeerDrops(ch chan<- *peerConnection) event.Subscription {
  274. return ps.peerDropFeed.Subscribe(ch)
  275. }
  276. // Reset iterates over the current peer set, and resets each of the known peers
  277. // to prepare for a next batch of block retrieval.
  278. func (ps *peerSet) Reset() {
  279. ps.lock.RLock()
  280. defer ps.lock.RUnlock()
  281. for _, peer := range ps.peers {
  282. peer.Reset()
  283. }
  284. }
  285. // Register injects a new peer into the working set, or returns an error if the
  286. // peer is already known.
  287. //
  288. // The method also sets the starting throughput values of the new peer to the
  289. // average of all existing peers, to give it a realistic chance of being used
  290. // for data retrievals.
  291. func (ps *peerSet) Register(p *peerConnection) error {
  292. // Register the new peer with some meaningful defaults
  293. ps.lock.Lock()
  294. if _, ok := ps.peers[p.id]; ok {
  295. ps.lock.Unlock()
  296. return errAlreadyRegistered
  297. }
  298. p.rates = msgrate.NewTracker(ps.rates.MeanCapacities(), ps.rates.MedianRoundTrip())
  299. if err := ps.rates.Track(p.id, p.rates); err != nil {
  300. ps.lock.Unlock()
  301. return err
  302. }
  303. ps.peers[p.id] = p
  304. ps.lock.Unlock()
  305. ps.newPeerFeed.Send(p)
  306. return nil
  307. }
  308. // Unregister removes a remote peer from the active set, disabling any further
  309. // actions to/from that particular entity.
  310. func (ps *peerSet) Unregister(id string) error {
  311. ps.lock.Lock()
  312. p, ok := ps.peers[id]
  313. if !ok {
  314. ps.lock.Unlock()
  315. return errNotRegistered
  316. }
  317. delete(ps.peers, id)
  318. ps.rates.Untrack(id)
  319. ps.lock.Unlock()
  320. ps.peerDropFeed.Send(p)
  321. return nil
  322. }
  323. // Peer retrieves the registered peer with the given id.
  324. func (ps *peerSet) Peer(id string) *peerConnection {
  325. ps.lock.RLock()
  326. defer ps.lock.RUnlock()
  327. return ps.peers[id]
  328. }
  329. // Len returns if the current number of peers in the set.
  330. func (ps *peerSet) Len() int {
  331. ps.lock.RLock()
  332. defer ps.lock.RUnlock()
  333. return len(ps.peers)
  334. }
  335. // AllPeers retrieves a flat list of all the peers within the set.
  336. func (ps *peerSet) AllPeers() []*peerConnection {
  337. ps.lock.RLock()
  338. defer ps.lock.RUnlock()
  339. list := make([]*peerConnection, 0, len(ps.peers))
  340. for _, p := range ps.peers {
  341. list = append(list, p)
  342. }
  343. return list
  344. }
  345. // HeaderIdlePeers retrieves a flat list of all the currently header-idle peers
  346. // within the active peer set, ordered by their reputation.
  347. func (ps *peerSet) HeaderIdlePeers() ([]*peerConnection, int) {
  348. idle := func(p *peerConnection) bool {
  349. return atomic.LoadInt32(&p.headerIdle) == 0
  350. }
  351. throughput := func(p *peerConnection) int {
  352. return p.rates.Capacity(eth.BlockHeadersMsg, time.Second)
  353. }
  354. return ps.idlePeers(eth.ETH66, eth.ETH67, idle, throughput)
  355. }
  356. // BodyIdlePeers retrieves a flat list of all the currently body-idle peers within
  357. // the active peer set, ordered by their reputation.
  358. func (ps *peerSet) BodyIdlePeers() ([]*peerConnection, int) {
  359. idle := func(p *peerConnection) bool {
  360. return atomic.LoadInt32(&p.blockIdle) == 0
  361. }
  362. throughput := func(p *peerConnection) int {
  363. return p.rates.Capacity(eth.BlockBodiesMsg, time.Second)
  364. }
  365. return ps.idlePeers(eth.ETH66, eth.ETH67, idle, throughput)
  366. }
  367. // ReceiptIdlePeers retrieves a flat list of all the currently receipt-idle peers
  368. // within the active peer set, ordered by their reputation.
  369. func (ps *peerSet) ReceiptIdlePeers() ([]*peerConnection, int) {
  370. idle := func(p *peerConnection) bool {
  371. return atomic.LoadInt32(&p.receiptIdle) == 0
  372. }
  373. throughput := func(p *peerConnection) int {
  374. return p.rates.Capacity(eth.ReceiptsMsg, time.Second)
  375. }
  376. return ps.idlePeers(eth.ETH66, eth.ETH67, idle, throughput)
  377. }
  378. // NodeDataIdlePeers retrieves a flat list of all the currently node-data-idle
  379. // peers within the active peer set, ordered by their reputation.
  380. func (ps *peerSet) NodeDataIdlePeers() ([]*peerConnection, int) {
  381. idle := func(p *peerConnection) bool {
  382. return atomic.LoadInt32(&p.stateIdle) == 0
  383. }
  384. throughput := func(p *peerConnection) int {
  385. return p.rates.Capacity(eth.NodeDataMsg, time.Second)
  386. }
  387. return ps.idlePeers(eth.ETH66, eth.ETH67, idle, throughput)
  388. }
  389. // idlePeers retrieves a flat list of all currently idle peers satisfying the
  390. // protocol version constraints, using the provided function to check idleness.
  391. // The resulting set of peers are sorted by their capacity.
  392. func (ps *peerSet) idlePeers(minProtocol, maxProtocol uint, idleCheck func(*peerConnection) bool, capacity func(*peerConnection) int) ([]*peerConnection, int) {
  393. ps.lock.RLock()
  394. defer ps.lock.RUnlock()
  395. var (
  396. total = 0
  397. idle = make([]*peerConnection, 0, len(ps.peers))
  398. tps = make([]int, 0, len(ps.peers))
  399. )
  400. for _, p := range ps.peers {
  401. if p.version >= minProtocol && p.version <= maxProtocol {
  402. if idleCheck(p) {
  403. idle = append(idle, p)
  404. tps = append(tps, capacity(p))
  405. }
  406. total++
  407. }
  408. }
  409. // And sort them
  410. sortPeers := &peerCapacitySort{idle, tps}
  411. sort.Sort(sortPeers)
  412. return sortPeers.p, total
  413. }
  414. // peerCapacitySort implements sort.Interface.
  415. // It sorts peer connections by capacity (descending).
  416. type peerCapacitySort struct {
  417. p []*peerConnection
  418. tp []int
  419. }
  420. func (ps *peerCapacitySort) Len() int {
  421. return len(ps.p)
  422. }
  423. func (ps *peerCapacitySort) Less(i, j int) bool {
  424. return ps.tp[i] > ps.tp[j]
  425. }
  426. func (ps *peerCapacitySort) Swap(i, j int) {
  427. ps.p[i], ps.p[j] = ps.p[j], ps.p[i]
  428. ps.tp[i], ps.tp[j] = ps.tp[j], ps.tp[i]
  429. }