handler.go 19 KB

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