handler.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. "errors"
  19. "math"
  20. "math/big"
  21. "sync"
  22. "sync/atomic"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/core"
  26. "github.com/ethereum/go-ethereum/core/forkid"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/eth/downloader"
  29. "github.com/ethereum/go-ethereum/eth/fetcher"
  30. "github.com/ethereum/go-ethereum/eth/protocols/diff"
  31. "github.com/ethereum/go-ethereum/eth/protocols/eth"
  32. "github.com/ethereum/go-ethereum/eth/protocols/snap"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/event"
  35. "github.com/ethereum/go-ethereum/log"
  36. "github.com/ethereum/go-ethereum/p2p"
  37. "github.com/ethereum/go-ethereum/params"
  38. "github.com/ethereum/go-ethereum/rlp"
  39. "github.com/ethereum/go-ethereum/trie"
  40. )
  41. const (
  42. // txChanSize is the size of channel listening to NewTxsEvent.
  43. // The number is referenced from the size of tx pool.
  44. txChanSize = 4096
  45. )
  46. var (
  47. syncChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the sync progress challenge
  48. )
  49. // txPool defines the methods needed from a transaction pool implementation to
  50. // support all the operations needed by the Ethereum chain protocols.
  51. type txPool interface {
  52. // Has returns an indicator whether txpool has a transaction
  53. // cached with the given hash.
  54. Has(hash common.Hash) bool
  55. // Get retrieves the transaction from local txpool with given
  56. // tx hash.
  57. Get(hash common.Hash) *types.Transaction
  58. // AddRemotes should add the given transactions to the pool.
  59. AddRemotes([]*types.Transaction) []error
  60. // Pending should return pending transactions.
  61. // The slice should be modifiable by the caller.
  62. Pending() (map[common.Address]types.Transactions, error)
  63. // SubscribeNewTxsEvent should return an event subscription of
  64. // NewTxsEvent and send events to the given channel.
  65. SubscribeNewTxsEvent(chan<- core.NewTxsEvent) event.Subscription
  66. }
  67. // handlerConfig is the collection of initialization parameters to create a full
  68. // node network handler.
  69. type handlerConfig struct {
  70. Database ethdb.Database // Database for direct sync insertions
  71. Chain *core.BlockChain // Blockchain to serve data from
  72. TxPool txPool // Transaction pool to propagate from
  73. Network uint64 // Network identifier to adfvertise
  74. Sync downloader.SyncMode // Whether to fast or full sync
  75. DiffSync bool // Whether to diff sync
  76. BloomCache uint64 // Megabytes to alloc for fast sync bloom
  77. EventMux *event.TypeMux // Legacy event mux, deprecate for `feed`
  78. Checkpoint *params.TrustedCheckpoint // Hard coded checkpoint for sync challenges
  79. Whitelist map[uint64]common.Hash // Hard coded whitelist for sync challenged
  80. DirectBroadcast bool
  81. }
  82. type handler struct {
  83. networkID uint64
  84. forkFilter forkid.Filter // Fork ID filter, constant across the lifetime of the node
  85. fastSync uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks)
  86. snapSync uint32 // Flag whether fast sync should operate on top of the snap protocol
  87. acceptTxs uint32 // Flag whether we're considered synchronised (enables transaction processing)
  88. directBroadcast bool
  89. diffSync bool // Flag whether diff sync should operate on top of the diff protocol
  90. checkpointNumber uint64 // Block number for the sync progress validator to cross reference
  91. checkpointHash common.Hash // Block hash for the sync progress validator to cross reference
  92. database ethdb.Database
  93. txpool txPool
  94. chain *core.BlockChain
  95. maxPeers int
  96. downloader *downloader.Downloader
  97. stateBloom *trie.SyncBloom
  98. blockFetcher *fetcher.BlockFetcher
  99. txFetcher *fetcher.TxFetcher
  100. peers *peerSet
  101. eventMux *event.TypeMux
  102. txsCh chan core.NewTxsEvent
  103. txsSub event.Subscription
  104. minedBlockSub *event.TypeMuxSubscription
  105. whitelist map[uint64]common.Hash
  106. // channels for fetcher, syncer, txsyncLoop
  107. txsyncCh chan *txsync
  108. quitSync chan struct{}
  109. chainSync *chainSyncer
  110. wg sync.WaitGroup
  111. peerWG sync.WaitGroup
  112. }
  113. // newHandler returns a handler for all Ethereum chain management protocol.
  114. func newHandler(config *handlerConfig) (*handler, error) {
  115. // Create the protocol manager with the base fields
  116. if config.EventMux == nil {
  117. config.EventMux = new(event.TypeMux) // Nicety initialization for tests
  118. }
  119. h := &handler{
  120. networkID: config.Network,
  121. forkFilter: forkid.NewFilter(config.Chain),
  122. eventMux: config.EventMux,
  123. database: config.Database,
  124. txpool: config.TxPool,
  125. chain: config.Chain,
  126. peers: newPeerSet(),
  127. whitelist: config.Whitelist,
  128. directBroadcast: config.DirectBroadcast,
  129. diffSync: config.DiffSync,
  130. txsyncCh: make(chan *txsync),
  131. quitSync: make(chan struct{}),
  132. }
  133. if config.Sync == downloader.FullSync {
  134. // The database seems empty as the current block is the genesis. Yet the fast
  135. // block is ahead, so fast sync was enabled for this node at a certain point.
  136. // The scenarios where this can happen is
  137. // * if the user manually (or via a bad block) rolled back a fast sync node
  138. // below the sync point.
  139. // * the last fast sync is not finished while user specifies a full sync this
  140. // time. But we don't have any recent state for full sync.
  141. // In these cases however it's safe to reenable fast sync.
  142. fullBlock, fastBlock := h.chain.CurrentBlock(), h.chain.CurrentFastBlock()
  143. if fullBlock.NumberU64() == 0 && fastBlock.NumberU64() > 0 {
  144. h.fastSync = uint32(1)
  145. log.Warn("Switch sync mode from full sync to fast sync")
  146. }
  147. } else {
  148. if h.chain.CurrentBlock().NumberU64() > 0 {
  149. // Print warning log if database is not empty to run fast sync.
  150. log.Warn("Switch sync mode from fast sync to full sync")
  151. } else {
  152. // If fast sync was requested and our database is empty, grant it
  153. h.fastSync = uint32(1)
  154. if config.Sync == downloader.SnapSync {
  155. h.snapSync = uint32(1)
  156. }
  157. }
  158. }
  159. // If we have trusted checkpoints, enforce them on the chain
  160. if config.Checkpoint != nil {
  161. h.checkpointNumber = (config.Checkpoint.SectionIndex+1)*params.CHTFrequency - 1
  162. h.checkpointHash = config.Checkpoint.SectionHead
  163. }
  164. // Construct the downloader (long sync) and its backing state bloom if fast
  165. // sync is requested. The downloader is responsible for deallocating the state
  166. // bloom when it's done.
  167. // Note: we don't enable it if snap-sync is performed, since it's very heavy
  168. // and the heal-portion of the snap sync is much lighter than fast. What we particularly
  169. // want to avoid, is a 90%-finished (but restarted) snap-sync to begin
  170. // indexing the entire trie
  171. if atomic.LoadUint32(&h.fastSync) == 1 && atomic.LoadUint32(&h.snapSync) == 0 {
  172. h.stateBloom = trie.NewSyncBloom(config.BloomCache, config.Database)
  173. }
  174. var downloadOptions []downloader.DownloadOption
  175. if h.diffSync {
  176. downloadOptions = append(downloadOptions, downloader.EnableDiffFetchOp(h.peers))
  177. }
  178. h.downloader = downloader.New(h.checkpointNumber, config.Database, h.stateBloom, h.eventMux, h.chain, nil, h.removePeer, downloadOptions...)
  179. // Construct the fetcher (short sync)
  180. validator := func(header *types.Header) error {
  181. return h.chain.Engine().VerifyHeader(h.chain, header, true)
  182. }
  183. heighter := func() uint64 {
  184. return h.chain.CurrentBlock().NumberU64()
  185. }
  186. inserter := func(blocks types.Blocks) (int, error) {
  187. // If sync hasn't reached the checkpoint yet, deny importing weird blocks.
  188. //
  189. // Ideally we would also compare the head block's timestamp and similarly reject
  190. // the propagated block if the head is too old. Unfortunately there is a corner
  191. // case when starting new networks, where the genesis might be ancient (0 unix)
  192. // which would prevent full nodes from accepting it.
  193. if h.chain.CurrentBlock().NumberU64() < h.checkpointNumber {
  194. log.Warn("Unsynced yet, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
  195. return 0, nil
  196. }
  197. // If fast sync is running, deny importing weird blocks. This is a problematic
  198. // clause when starting up a new network, because fast-syncing miners might not
  199. // accept each others' blocks until a restart. Unfortunately we haven't figured
  200. // out a way yet where nodes can decide unilaterally whether the network is new
  201. // or not. This should be fixed if we figure out a solution.
  202. if atomic.LoadUint32(&h.fastSync) == 1 {
  203. log.Warn("Fast syncing, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
  204. return 0, nil
  205. }
  206. n, err := h.chain.InsertChain(blocks)
  207. if err == nil {
  208. atomic.StoreUint32(&h.acceptTxs, 1) // Mark initial sync done on any fetcher import
  209. }
  210. return n, err
  211. }
  212. h.blockFetcher = fetcher.NewBlockFetcher(false, nil, h.chain.GetBlockByHash, validator, h.BroadcastBlock, heighter, nil, inserter, h.removePeer)
  213. fetchTx := func(peer string, hashes []common.Hash) error {
  214. p := h.peers.peer(peer)
  215. if p == nil {
  216. return errors.New("unknown peer")
  217. }
  218. return p.RequestTxs(hashes)
  219. }
  220. h.txFetcher = fetcher.NewTxFetcher(h.txpool.Has, h.txpool.AddRemotes, fetchTx)
  221. h.chainSync = newChainSyncer(h)
  222. return h, nil
  223. }
  224. // runEthPeer registers an eth peer into the joint eth/snap peerset, adds it to
  225. // various subsistems and starts handling messages.
  226. func (h *handler) runEthPeer(peer *eth.Peer, handler eth.Handler) error {
  227. // If the peer has a `snap` extension, wait for it to connect so we can have
  228. // a uniform initialization/teardown mechanism
  229. snap, err := h.peers.waitSnapExtension(peer)
  230. if err != nil {
  231. peer.Log().Error("Snapshot extension barrier failed", "err", err)
  232. return err
  233. }
  234. diff, err := h.peers.waitDiffExtension(peer)
  235. if err != nil {
  236. peer.Log().Error("Diff extension barrier failed", "err", err)
  237. return err
  238. }
  239. // TODO(karalabe): Not sure why this is needed
  240. if !h.chainSync.handlePeerEvent(peer) {
  241. return p2p.DiscQuitting
  242. }
  243. h.peerWG.Add(1)
  244. defer h.peerWG.Done()
  245. // Execute the Ethereum handshake
  246. var (
  247. genesis = h.chain.Genesis()
  248. head = h.chain.CurrentHeader()
  249. hash = head.Hash()
  250. number = head.Number.Uint64()
  251. td = h.chain.GetTd(hash, number)
  252. )
  253. forkID := forkid.NewID(h.chain.Config(), h.chain.Genesis().Hash(), h.chain.CurrentHeader().Number.Uint64())
  254. if err := peer.Handshake(h.networkID, td, hash, genesis.Hash(), forkID, h.forkFilter); err != nil {
  255. peer.Log().Debug("Ethereum handshake failed", "err", err)
  256. return err
  257. }
  258. reject := false // reserved peer slots
  259. if atomic.LoadUint32(&h.snapSync) == 1 {
  260. if snap == nil {
  261. // If we are running snap-sync, we want to reserve roughly half the peer
  262. // slots for peers supporting the snap protocol.
  263. // The logic here is; we only allow up to 5 more non-snap peers than snap-peers.
  264. if all, snp := h.peers.len(), h.peers.snapLen(); all-snp > snp+5 {
  265. reject = true
  266. }
  267. }
  268. }
  269. // Ignore maxPeers if this is a trusted peer
  270. if !peer.Peer.Info().Network.Trusted {
  271. if reject || h.peers.len() >= h.maxPeers {
  272. return p2p.DiscTooManyPeers
  273. }
  274. }
  275. peer.Log().Debug("Ethereum peer connected", "name", peer.Name())
  276. // Register the peer locally
  277. if err := h.peers.registerPeer(peer, snap, diff); err != nil {
  278. peer.Log().Error("Ethereum peer registration failed", "err", err)
  279. return err
  280. }
  281. defer h.removePeer(peer.ID())
  282. p := h.peers.peer(peer.ID())
  283. if p == nil {
  284. return errors.New("peer dropped during handling")
  285. }
  286. // Register the peer in the downloader. If the downloader considers it banned, we disconnect
  287. if err := h.downloader.RegisterPeer(peer.ID(), peer.Version(), peer); err != nil {
  288. peer.Log().Error("Failed to register peer in eth syncer", "err", err)
  289. return err
  290. }
  291. if snap != nil {
  292. if err := h.downloader.SnapSyncer.Register(snap); err != nil {
  293. peer.Log().Error("Failed to register peer in snap syncer", "err", err)
  294. return err
  295. }
  296. }
  297. h.chainSync.handlePeerEvent(peer)
  298. // Propagate existing transactions. new transactions appearing
  299. // after this will be sent via broadcasts.
  300. h.syncTransactions(peer)
  301. // If we have a trusted CHT, reject all peers below that (avoid fast sync eclipse)
  302. if h.checkpointHash != (common.Hash{}) {
  303. // Request the peer's checkpoint header for chain height/weight validation
  304. if err := peer.RequestHeadersByNumber(h.checkpointNumber, 1, 0, false); err != nil {
  305. return err
  306. }
  307. // Start a timer to disconnect if the peer doesn't reply in time
  308. p.syncDrop = time.AfterFunc(syncChallengeTimeout, func() {
  309. peer.Log().Warn("Checkpoint challenge timed out, dropping", "addr", peer.RemoteAddr(), "type", peer.Name())
  310. h.removePeer(peer.ID())
  311. })
  312. // Make sure it's cleaned up if the peer dies off
  313. defer func() {
  314. if p.syncDrop != nil {
  315. p.syncDrop.Stop()
  316. p.syncDrop = nil
  317. }
  318. }()
  319. }
  320. // If we have any explicit whitelist block hashes, request them
  321. for number := range h.whitelist {
  322. if err := peer.RequestHeadersByNumber(number, 1, 0, false); err != nil {
  323. return err
  324. }
  325. }
  326. // Handle incoming messages until the connection is torn down
  327. return handler(peer)
  328. }
  329. // runSnapExtension registers a `snap` peer into the joint eth/snap peerset and
  330. // starts handling inbound messages. As `snap` is only a satellite protocol to
  331. // `eth`, all subsystem registrations and lifecycle management will be done by
  332. // the main `eth` handler to prevent strange races.
  333. func (h *handler) runSnapExtension(peer *snap.Peer, handler snap.Handler) error {
  334. h.peerWG.Add(1)
  335. defer h.peerWG.Done()
  336. if err := h.peers.registerSnapExtension(peer); err != nil {
  337. peer.Log().Error("Snapshot extension registration failed", "err", err)
  338. return err
  339. }
  340. return handler(peer)
  341. }
  342. // runDiffExtension registers a `diff` peer into the joint eth/diff peerset and
  343. // starts handling inbound messages. As `diff` is only a satellite protocol to
  344. // `eth`, all subsystem registrations and lifecycle management will be done by
  345. // the main `eth` handler to prevent strange races.
  346. func (h *handler) runDiffExtension(peer *diff.Peer, handler diff.Handler) error {
  347. h.peerWG.Add(1)
  348. defer h.peerWG.Done()
  349. if err := h.peers.registerDiffExtension(peer); err != nil {
  350. peer.Log().Error("Diff extension registration failed", "err", err)
  351. return err
  352. }
  353. return handler(peer)
  354. }
  355. // removePeer unregisters a peer from the downloader and fetchers, removes it from
  356. // the set of tracked peers and closes the network connection to it.
  357. func (h *handler) removePeer(id string) {
  358. // Create a custom logger to avoid printing the entire id
  359. var logger log.Logger
  360. if len(id) < 16 {
  361. // Tests use short IDs, don't choke on them
  362. logger = log.New("peer", id)
  363. } else {
  364. logger = log.New("peer", id[:8])
  365. }
  366. // Abort if the peer does not exist
  367. peer := h.peers.peer(id)
  368. if peer == nil {
  369. logger.Error("Ethereum peer removal failed", "err", errPeerNotRegistered)
  370. return
  371. }
  372. // Remove the `eth` peer if it exists
  373. logger.Debug("Removing Ethereum peer", "snap", peer.snapExt != nil)
  374. // Remove the `snap` extension if it exists
  375. if peer.snapExt != nil {
  376. h.downloader.SnapSyncer.Unregister(id)
  377. }
  378. h.downloader.UnregisterPeer(id)
  379. h.txFetcher.Drop(id)
  380. if err := h.peers.unregisterPeer(id); err != nil {
  381. logger.Error("Ethereum peer removal failed", "err", err)
  382. }
  383. // Hard disconnect at the networking layer
  384. peer.Peer.Disconnect(p2p.DiscUselessPeer)
  385. }
  386. func (h *handler) Start(maxPeers int) {
  387. h.maxPeers = maxPeers
  388. // broadcast transactions
  389. h.wg.Add(1)
  390. h.txsCh = make(chan core.NewTxsEvent, txChanSize)
  391. h.txsSub = h.txpool.SubscribeNewTxsEvent(h.txsCh)
  392. go h.txBroadcastLoop()
  393. // broadcast mined blocks
  394. h.wg.Add(1)
  395. h.minedBlockSub = h.eventMux.Subscribe(core.NewMinedBlockEvent{})
  396. go h.minedBroadcastLoop()
  397. // start sync handlers
  398. h.wg.Add(2)
  399. go h.chainSync.loop()
  400. go h.txsyncLoop64() // TODO(karalabe): Legacy initial tx echange, drop with eth/64.
  401. }
  402. func (h *handler) Stop() {
  403. h.txsSub.Unsubscribe() // quits txBroadcastLoop
  404. h.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
  405. // Quit chainSync and txsync64.
  406. // After this is done, no new peers will be accepted.
  407. close(h.quitSync)
  408. h.wg.Wait()
  409. // Disconnect existing sessions.
  410. // This also closes the gate for any new registrations on the peer set.
  411. // sessions which are already established but not added to h.peers yet
  412. // will exit when they try to register.
  413. h.peers.close()
  414. h.peerWG.Wait()
  415. log.Info("Ethereum protocol stopped")
  416. }
  417. // BroadcastBlock will either propagate a block to a subset of its peers, or
  418. // will only announce its availability (depending what's requested).
  419. func (h *handler) BroadcastBlock(block *types.Block, propagate bool) {
  420. hash := block.Hash()
  421. peers := h.peers.peersWithoutBlock(hash)
  422. // If propagation is requested, send to a subset of the peer
  423. if propagate {
  424. // Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
  425. var td *big.Int
  426. if parent := h.chain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
  427. td = new(big.Int).Add(block.Difficulty(), h.chain.GetTd(block.ParentHash(), block.NumberU64()-1))
  428. } else {
  429. log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
  430. return
  431. }
  432. // Send the block to a subset of our peers
  433. var transfer []*ethPeer
  434. if h.directBroadcast {
  435. transfer = peers[:]
  436. } else {
  437. transfer = peers[:int(math.Sqrt(float64(len(peers))))]
  438. }
  439. diff := h.chain.GetDiffLayerRLP(block.Hash())
  440. for _, peer := range transfer {
  441. if len(diff) != 0 && peer.diffExt != nil {
  442. // difflayer should send before block
  443. peer.diffExt.SendDiffLayers([]rlp.RawValue{diff})
  444. }
  445. peer.AsyncSendNewBlock(block, td)
  446. }
  447. log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  448. return
  449. }
  450. // Otherwise if the block is indeed in out own chain, announce it
  451. if h.chain.HasBlock(hash, block.NumberU64()) {
  452. for _, peer := range peers {
  453. peer.AsyncSendNewBlockHash(block)
  454. }
  455. log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  456. }
  457. }
  458. // BroadcastTransactions will propagate a batch of transactions
  459. // - To a square root of all peers
  460. // - And, separately, as announcements to all peers which are not known to
  461. // already have the given transaction.
  462. func (h *handler) BroadcastTransactions(txs types.Transactions) {
  463. var (
  464. annoCount int // Count of announcements made
  465. annoPeers int
  466. directCount int // Count of the txs sent directly to peers
  467. directPeers int // Count of the peers that were sent transactions directly
  468. txset = make(map[*ethPeer][]common.Hash) // Set peer->hash to transfer directly
  469. annos = make(map[*ethPeer][]common.Hash) // Set peer->hash to announce
  470. )
  471. // Broadcast transactions to a batch of peers not knowing about it
  472. for _, tx := range txs {
  473. peers := h.peers.peersWithoutTransaction(tx.Hash())
  474. // Send the tx unconditionally to a subset of our peers
  475. numDirect := int(math.Sqrt(float64(len(peers))))
  476. for _, peer := range peers[:numDirect] {
  477. txset[peer] = append(txset[peer], tx.Hash())
  478. }
  479. // For the remaining peers, send announcement only
  480. for _, peer := range peers[numDirect:] {
  481. annos[peer] = append(annos[peer], tx.Hash())
  482. }
  483. }
  484. for peer, hashes := range txset {
  485. directPeers++
  486. directCount += len(hashes)
  487. peer.AsyncSendTransactions(hashes)
  488. }
  489. for peer, hashes := range annos {
  490. annoPeers++
  491. annoCount += len(hashes)
  492. peer.AsyncSendPooledTransactionHashes(hashes)
  493. }
  494. log.Debug("Transaction broadcast", "txs", len(txs),
  495. "announce packs", annoPeers, "announced hashes", annoCount,
  496. "tx packs", directPeers, "broadcast txs", directCount)
  497. }
  498. // minedBroadcastLoop sends mined blocks to connected peers.
  499. func (h *handler) minedBroadcastLoop() {
  500. defer h.wg.Done()
  501. for obj := range h.minedBlockSub.Chan() {
  502. if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok {
  503. h.BroadcastBlock(ev.Block, true) // First propagate block to peers
  504. h.BroadcastBlock(ev.Block, false) // Only then announce to the rest
  505. }
  506. }
  507. }
  508. // txBroadcastLoop announces new transactions to connected peers.
  509. func (h *handler) txBroadcastLoop() {
  510. defer h.wg.Done()
  511. for {
  512. select {
  513. case event := <-h.txsCh:
  514. h.BroadcastTransactions(event.Txs)
  515. case <-h.txsSub.Err():
  516. return
  517. }
  518. }
  519. }