handler.go 19 KB

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