sync.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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/big"
  19. "math/rand"
  20. "sync/atomic"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/rawdb"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/eth/downloader"
  26. "github.com/ethereum/go-ethereum/eth/protocols/eth"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/p2p/enode"
  29. )
  30. const (
  31. forceSyncCycle = 10 * time.Second // Time interval to force syncs, even if few peers are available
  32. defaultMinSyncPeers = 5 // Amount of peers desired to start syncing
  33. // This is the target size for the packs of transactions sent by txsyncLoop64.
  34. // A pack can get larger than this if a single transactions exceeds this size.
  35. txsyncPackSize = 100 * 1024
  36. )
  37. type txsync struct {
  38. p *eth.Peer
  39. txs []*types.Transaction
  40. }
  41. // syncTransactions starts sending all currently pending transactions to the given peer.
  42. func (h *handler) syncTransactions(p *eth.Peer) {
  43. // Assemble the set of transaction to broadcast or announce to the remote
  44. // peer. Fun fact, this is quite an expensive operation as it needs to sort
  45. // the transactions if the sorting is not cached yet. However, with a random
  46. // order, insertions could overflow the non-executable queues and get dropped.
  47. //
  48. // TODO(karalabe): Figure out if we could get away with random order somehow
  49. var txs types.Transactions
  50. pending, _ := h.txpool.Pending()
  51. for _, batch := range pending {
  52. txs = append(txs, batch...)
  53. }
  54. if len(txs) == 0 {
  55. return
  56. }
  57. // The eth/65 protocol introduces proper transaction announcements, so instead
  58. // of dripping transactions across multiple peers, just send the entire list as
  59. // an announcement and let the remote side decide what they need (likely nothing).
  60. if p.Version() >= eth.ETH65 {
  61. hashes := make([]common.Hash, len(txs))
  62. for i, tx := range txs {
  63. hashes[i] = tx.Hash()
  64. }
  65. p.AsyncSendPooledTransactionHashes(hashes)
  66. return
  67. }
  68. // Out of luck, peer is running legacy protocols, drop the txs over
  69. select {
  70. case h.txsyncCh <- &txsync{p: p, txs: txs}:
  71. case <-h.quitSync:
  72. }
  73. }
  74. // txsyncLoop64 takes care of the initial transaction sync for each new
  75. // connection. When a new peer appears, we relay all currently pending
  76. // transactions. In order to minimise egress bandwidth usage, we send
  77. // the transactions in small packs to one peer at a time.
  78. func (h *handler) txsyncLoop64() {
  79. defer h.wg.Done()
  80. var (
  81. pending = make(map[enode.ID]*txsync)
  82. sending = false // whether a send is active
  83. pack = new(txsync) // the pack that is being sent
  84. done = make(chan error, 1) // result of the send
  85. )
  86. // send starts a sending a pack of transactions from the sync.
  87. send := func(s *txsync) {
  88. if s.p.Version() >= eth.ETH65 {
  89. panic("initial transaction syncer running on eth/65+")
  90. }
  91. // Fill pack with transactions up to the target size.
  92. size := common.StorageSize(0)
  93. pack.p = s.p
  94. pack.txs = pack.txs[:0]
  95. for i := 0; i < len(s.txs) && size < txsyncPackSize; i++ {
  96. pack.txs = append(pack.txs, s.txs[i])
  97. size += s.txs[i].Size()
  98. }
  99. // Remove the transactions that will be sent.
  100. s.txs = s.txs[:copy(s.txs, s.txs[len(pack.txs):])]
  101. if len(s.txs) == 0 {
  102. delete(pending, s.p.Peer.ID())
  103. }
  104. // Send the pack in the background.
  105. s.p.Log().Trace("Sending batch of transactions", "count", len(pack.txs), "bytes", size)
  106. sending = true
  107. go func() { done <- pack.p.SendTransactions(pack.txs) }()
  108. }
  109. // pick chooses the next pending sync.
  110. pick := func() *txsync {
  111. if len(pending) == 0 {
  112. return nil
  113. }
  114. n := rand.Intn(len(pending)) + 1
  115. for _, s := range pending {
  116. if n--; n == 0 {
  117. return s
  118. }
  119. }
  120. return nil
  121. }
  122. for {
  123. select {
  124. case s := <-h.txsyncCh:
  125. pending[s.p.Peer.ID()] = s
  126. if !sending {
  127. send(s)
  128. }
  129. case err := <-done:
  130. sending = false
  131. // Stop tracking peers that cause send failures.
  132. if err != nil {
  133. pack.p.Log().Debug("Transaction send failed", "err", err)
  134. delete(pending, pack.p.Peer.ID())
  135. }
  136. // Schedule the next send.
  137. if s := pick(); s != nil {
  138. send(s)
  139. }
  140. case <-h.quitSync:
  141. return
  142. }
  143. }
  144. }
  145. // chainSyncer coordinates blockchain sync components.
  146. type chainSyncer struct {
  147. handler *handler
  148. force *time.Timer
  149. forced bool // true when force timer fired
  150. peerEventCh chan struct{}
  151. doneCh chan error // non-nil when sync is running
  152. }
  153. // chainSyncOp is a scheduled sync operation.
  154. type chainSyncOp struct {
  155. mode downloader.SyncMode
  156. peer *eth.Peer
  157. td *big.Int
  158. head common.Hash
  159. }
  160. // newChainSyncer creates a chainSyncer.
  161. func newChainSyncer(handler *handler) *chainSyncer {
  162. return &chainSyncer{
  163. handler: handler,
  164. peerEventCh: make(chan struct{}),
  165. }
  166. }
  167. // handlePeerEvent notifies the syncer about a change in the peer set.
  168. // This is called for new peers and every time a peer announces a new
  169. // chain head.
  170. func (cs *chainSyncer) handlePeerEvent(peer *eth.Peer) bool {
  171. select {
  172. case cs.peerEventCh <- struct{}{}:
  173. return true
  174. case <-cs.handler.quitSync:
  175. return false
  176. }
  177. }
  178. // loop runs in its own goroutine and launches the sync when necessary.
  179. func (cs *chainSyncer) loop() {
  180. defer cs.handler.wg.Done()
  181. cs.handler.blockFetcher.Start()
  182. cs.handler.txFetcher.Start()
  183. defer cs.handler.blockFetcher.Stop()
  184. defer cs.handler.txFetcher.Stop()
  185. defer cs.handler.downloader.Terminate()
  186. // The force timer lowers the peer count threshold down to one when it fires.
  187. // This ensures we'll always start sync even if there aren't enough peers.
  188. cs.force = time.NewTimer(forceSyncCycle)
  189. defer cs.force.Stop()
  190. for {
  191. if op := cs.nextSyncOp(); op != nil {
  192. cs.startSync(op)
  193. }
  194. select {
  195. case <-cs.peerEventCh:
  196. // Peer information changed, recheck.
  197. case <-cs.doneCh:
  198. cs.doneCh = nil
  199. cs.force.Reset(forceSyncCycle)
  200. cs.forced = false
  201. case <-cs.force.C:
  202. cs.forced = true
  203. case <-cs.handler.quitSync:
  204. // Disable all insertion on the blockchain. This needs to happen before
  205. // terminating the downloader because the downloader waits for blockchain
  206. // inserts, and these can take a long time to finish.
  207. cs.handler.chain.StopInsert()
  208. cs.handler.downloader.Terminate()
  209. if cs.doneCh != nil {
  210. <-cs.doneCh
  211. }
  212. return
  213. }
  214. }
  215. }
  216. // nextSyncOp determines whether sync is required at this time.
  217. func (cs *chainSyncer) nextSyncOp() *chainSyncOp {
  218. if cs.doneCh != nil {
  219. return nil // Sync already running.
  220. }
  221. // Ensure we're at minimum peer count.
  222. minPeers := defaultMinSyncPeers
  223. if cs.forced {
  224. minPeers = 1
  225. } else if minPeers > cs.handler.maxPeers {
  226. minPeers = cs.handler.maxPeers
  227. }
  228. if cs.handler.peers.len() < minPeers {
  229. return nil
  230. }
  231. // We have enough peers, check TD
  232. peer := cs.handler.peers.peerWithHighestTD()
  233. if peer == nil {
  234. return nil
  235. }
  236. mode, ourTD := cs.modeAndLocalHead()
  237. if mode == downloader.FastSync && atomic.LoadUint32(&cs.handler.snapSync) == 1 {
  238. // Fast sync via the snap protocol
  239. mode = downloader.SnapSync
  240. }
  241. op := peerToSyncOp(mode, peer)
  242. if op.td.Cmp(ourTD) <= 0 {
  243. return nil // We're in sync.
  244. }
  245. return op
  246. }
  247. func peerToSyncOp(mode downloader.SyncMode, p *eth.Peer) *chainSyncOp {
  248. peerHead, peerTD := p.Head()
  249. return &chainSyncOp{mode: mode, peer: p, td: peerTD, head: peerHead}
  250. }
  251. func (cs *chainSyncer) modeAndLocalHead() (downloader.SyncMode, *big.Int) {
  252. // If we're in fast sync mode, return that directly
  253. if atomic.LoadUint32(&cs.handler.fastSync) == 1 {
  254. block := cs.handler.chain.CurrentFastBlock()
  255. td := cs.handler.chain.GetTdByHash(block.Hash())
  256. return downloader.FastSync, td
  257. }
  258. // We are probably in full sync, but we might have rewound to before the
  259. // fast sync pivot, check if we should reenable
  260. if pivot := rawdb.ReadLastPivotNumber(cs.handler.database); pivot != nil {
  261. if head := cs.handler.chain.CurrentBlock(); head.NumberU64() < *pivot {
  262. block := cs.handler.chain.CurrentFastBlock()
  263. td := cs.handler.chain.GetTdByHash(block.Hash())
  264. return downloader.FastSync, td
  265. }
  266. }
  267. // Nope, we're really full syncing
  268. head := cs.handler.chain.CurrentHeader()
  269. td := cs.handler.chain.GetTd(head.Hash(), head.Number.Uint64())
  270. return downloader.FullSync, td
  271. }
  272. // startSync launches doSync in a new goroutine.
  273. func (cs *chainSyncer) startSync(op *chainSyncOp) {
  274. cs.doneCh = make(chan error, 1)
  275. go func() { cs.doneCh <- cs.handler.doSync(op) }()
  276. }
  277. // doSync synchronizes the local blockchain with a remote peer.
  278. func (h *handler) doSync(op *chainSyncOp) error {
  279. if op.mode == downloader.FastSync || op.mode == downloader.SnapSync {
  280. // Before launch the fast sync, we have to ensure user uses the same
  281. // txlookup limit.
  282. // The main concern here is: during the fast sync Geth won't index the
  283. // block(generate tx indices) before the HEAD-limit. But if user changes
  284. // the limit in the next fast sync(e.g. user kill Geth manually and
  285. // restart) then it will be hard for Geth to figure out the oldest block
  286. // has been indexed. So here for the user-experience wise, it's non-optimal
  287. // that user can't change limit during the fast sync. If changed, Geth
  288. // will just blindly use the original one.
  289. limit := h.chain.TxLookupLimit()
  290. if stored := rawdb.ReadFastTxLookupLimit(h.database); stored == nil {
  291. rawdb.WriteFastTxLookupLimit(h.database, limit)
  292. } else if *stored != limit {
  293. h.chain.SetTxLookupLimit(*stored)
  294. log.Warn("Update txLookup limit", "provided", limit, "updated", *stored)
  295. }
  296. }
  297. // Run the sync cycle, and disable fast sync if we're past the pivot block
  298. err := h.downloader.Synchronise(op.peer.ID(), op.head, op.td, op.mode)
  299. if err != nil {
  300. return err
  301. }
  302. if atomic.LoadUint32(&h.fastSync) == 1 {
  303. log.Info("Fast sync complete, auto disabling")
  304. atomic.StoreUint32(&h.fastSync, 0)
  305. }
  306. if atomic.LoadUint32(&h.snapSync) == 1 {
  307. log.Info("Snap sync complete, auto disabling")
  308. atomic.StoreUint32(&h.snapSync, 0)
  309. }
  310. // If we've successfully finished a sync cycle and passed any required checkpoint,
  311. // enable accepting transactions from the network.
  312. head := h.chain.CurrentBlock()
  313. if head.NumberU64() >= h.checkpointNumber {
  314. // Checkpoint passed, sanity check the timestamp to have a fallback mechanism
  315. // for non-checkpointed (number = 0) private networks.
  316. if head.Time() >= uint64(time.Now().AddDate(0, -1, 0).Unix()) {
  317. atomic.StoreUint32(&h.acceptTxs, 1)
  318. }
  319. }
  320. if head.NumberU64() > 0 {
  321. // We've completed a sync cycle, notify all peers of new state. This path is
  322. // essential in star-topology networks where a gateway node needs to notify
  323. // all its out-of-date peers of the availability of a new block. This failure
  324. // scenario will most often crop up in private and hackathon networks with
  325. // degenerate connectivity, but it should be healthy for the mainnet too to
  326. // more reliably update peers or the local TD state.
  327. h.BroadcastBlock(head, false)
  328. }
  329. return nil
  330. }