sync.go 5.3 KB

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