handler.go 23 KB

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