sync.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. package eth
  17. import (
  18. "math/rand"
  19. "sync/atomic"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core/types"
  23. "github.com/ethereum/go-ethereum/eth/downloader"
  24. "github.com/ethereum/go-ethereum/logger"
  25. "github.com/ethereum/go-ethereum/logger/glog"
  26. "github.com/ethereum/go-ethereum/p2p/discover"
  27. )
  28. const (
  29. forceSyncCycle = 10 * time.Second // Time interval to force syncs, even if few peers are available
  30. minDesiredPeerCount = 5 // Amount of peers desired to start syncing
  31. // This is the target size for the packs of transactions sent by txsyncLoop.
  32. // A pack can get larger than this if a single transactions exceeds this size.
  33. txsyncPackSize = 100 * 1024
  34. )
  35. type txsync struct {
  36. p *peer
  37. txs []*types.Transaction
  38. }
  39. // syncTransactions starts sending all currently pending transactions to the given peer.
  40. func (pm *ProtocolManager) syncTransactions(p *peer) {
  41. var txs types.Transactions
  42. pending, _ := pm.txpool.Pending()
  43. for _, batch := range pending {
  44. txs = append(txs, batch...)
  45. }
  46. if len(txs) == 0 {
  47. return
  48. }
  49. select {
  50. case pm.txsyncCh <- &txsync{p, txs}:
  51. case <-pm.quitSync:
  52. }
  53. }
  54. // txsyncLoop takes care of the initial transaction sync for each new
  55. // connection. When a new peer appears, we relay all currently pending
  56. // transactions. In order to minimise egress bandwidth usage, we send
  57. // the transactions in small packs to one peer at a time.
  58. func (pm *ProtocolManager) txsyncLoop() {
  59. var (
  60. pending = make(map[discover.NodeID]*txsync)
  61. sending = false // whether a send is active
  62. pack = new(txsync) // the pack that is being sent
  63. done = make(chan error, 1) // result of the send
  64. )
  65. // send starts a sending a pack of transactions from the sync.
  66. send := func(s *txsync) {
  67. // Fill pack with transactions up to the target size.
  68. size := common.StorageSize(0)
  69. pack.p = s.p
  70. pack.txs = pack.txs[:0]
  71. for i := 0; i < len(s.txs) && size < txsyncPackSize; i++ {
  72. pack.txs = append(pack.txs, s.txs[i])
  73. size += s.txs[i].Size()
  74. }
  75. // Remove the transactions that will be sent.
  76. s.txs = s.txs[:copy(s.txs, s.txs[len(pack.txs):])]
  77. if len(s.txs) == 0 {
  78. delete(pending, s.p.ID())
  79. }
  80. // Send the pack in the background.
  81. glog.V(logger.Detail).Infof("%v: sending %d transactions (%v)", s.p.Peer, len(pack.txs), size)
  82. sending = true
  83. go func() { done <- pack.p.SendTransactions(pack.txs) }()
  84. }
  85. // pick chooses the next pending sync.
  86. pick := func() *txsync {
  87. if len(pending) == 0 {
  88. return nil
  89. }
  90. n := rand.Intn(len(pending)) + 1
  91. for _, s := range pending {
  92. if n--; n == 0 {
  93. return s
  94. }
  95. }
  96. return nil
  97. }
  98. for {
  99. select {
  100. case s := <-pm.txsyncCh:
  101. pending[s.p.ID()] = s
  102. if !sending {
  103. send(s)
  104. }
  105. case err := <-done:
  106. sending = false
  107. // Stop tracking peers that cause send failures.
  108. if err != nil {
  109. glog.V(logger.Debug).Infof("%v: tx send failed: %v", pack.p.Peer, err)
  110. delete(pending, pack.p.ID())
  111. }
  112. // Schedule the next send.
  113. if s := pick(); s != nil {
  114. send(s)
  115. }
  116. case <-pm.quitSync:
  117. return
  118. }
  119. }
  120. }
  121. // syncer is responsible for periodically synchronising with the network, both
  122. // downloading hashes and blocks as well as handling the announcement handler.
  123. func (pm *ProtocolManager) syncer() {
  124. // Start and ensure cleanup of sync mechanisms
  125. pm.fetcher.Start()
  126. defer pm.fetcher.Stop()
  127. defer pm.downloader.Terminate()
  128. // Wait for different events to fire synchronisation operations
  129. forceSync := time.Tick(forceSyncCycle)
  130. for {
  131. select {
  132. case <-pm.newPeerCh:
  133. // Make sure we have peers to select from, then sync
  134. if pm.peers.Len() < minDesiredPeerCount {
  135. break
  136. }
  137. go pm.synchronise(pm.peers.BestPeer())
  138. case <-forceSync:
  139. // Force a sync even if not enough peers are present
  140. go pm.synchronise(pm.peers.BestPeer())
  141. case <-pm.noMorePeers:
  142. return
  143. }
  144. }
  145. }
  146. // synchronise tries to sync up our local block chain with a remote peer.
  147. func (pm *ProtocolManager) synchronise(peer *peer) {
  148. // Short circuit if no peers are available
  149. if peer == nil {
  150. return
  151. }
  152. // Make sure the peer's TD is higher than our own
  153. currentBlock := pm.blockchain.CurrentBlock()
  154. td := pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  155. pHead, pTd := peer.Head()
  156. if pTd.Cmp(td) <= 0 {
  157. return
  158. }
  159. // Otherwise try to sync with the downloader
  160. mode := downloader.FullSync
  161. if atomic.LoadUint32(&pm.fastSync) == 1 {
  162. mode = downloader.FastSync
  163. }
  164. if err := pm.downloader.Synchronise(peer.id, pHead, pTd, mode); err != nil {
  165. return
  166. }
  167. atomic.StoreUint32(&pm.synced, 1) // Mark initial sync done
  168. // If fast sync was enabled, and we synced up, disable it
  169. if atomic.LoadUint32(&pm.fastSync) == 1 {
  170. // Disable fast sync if we indeed have something in our chain
  171. if pm.blockchain.CurrentBlock().NumberU64() > 0 {
  172. glog.V(logger.Info).Infof("fast sync complete, auto disabling")
  173. atomic.StoreUint32(&pm.fastSync, 0)
  174. }
  175. }
  176. }