handler.go 21 KB

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