handler.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. if atomic.LoadUint32(&h.fastSync) == 1 {
  160. h.stateBloom = trie.NewSyncBloom(config.BloomCache, config.Database)
  161. }
  162. h.downloader = downloader.New(h.checkpointNumber, config.Database, h.stateBloom, h.eventMux, h.chain, nil, h.removePeer)
  163. // Construct the fetcher (short sync)
  164. validator := func(header *types.Header) error {
  165. return h.chain.Engine().VerifyHeader(h.chain, header, true)
  166. }
  167. heighter := func() uint64 {
  168. return h.chain.CurrentBlock().NumberU64()
  169. }
  170. inserter := func(blocks types.Blocks) (int, error) {
  171. // If sync hasn't reached the checkpoint yet, deny importing weird blocks.
  172. //
  173. // Ideally we would also compare the head block's timestamp and similarly reject
  174. // the propagated block if the head is too old. Unfortunately there is a corner
  175. // case when starting new networks, where the genesis might be ancient (0 unix)
  176. // which would prevent full nodes from accepting it.
  177. if h.chain.CurrentBlock().NumberU64() < h.checkpointNumber {
  178. log.Warn("Unsynced yet, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
  179. return 0, nil
  180. }
  181. // If fast sync is running, deny importing weird blocks. This is a problematic
  182. // clause when starting up a new network, because fast-syncing miners might not
  183. // accept each others' blocks until a restart. Unfortunately we haven't figured
  184. // out a way yet where nodes can decide unilaterally whether the network is new
  185. // or not. This should be fixed if we figure out a solution.
  186. if atomic.LoadUint32(&h.fastSync) == 1 {
  187. log.Warn("Fast syncing, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
  188. return 0, nil
  189. }
  190. n, err := h.chain.InsertChain(blocks)
  191. if err == nil {
  192. atomic.StoreUint32(&h.acceptTxs, 1) // Mark initial sync done on any fetcher import
  193. }
  194. return n, err
  195. }
  196. h.blockFetcher = fetcher.NewBlockFetcher(false, nil, h.chain.GetBlockByHash, validator, h.BroadcastBlock, heighter, nil, inserter, h.removePeer)
  197. fetchTx := func(peer string, hashes []common.Hash) error {
  198. p := h.peers.peer(peer)
  199. if p == nil {
  200. return errors.New("unknown peer")
  201. }
  202. return p.RequestTxs(hashes)
  203. }
  204. h.txFetcher = fetcher.NewTxFetcher(h.txpool.Has, h.txpool.AddRemotes, fetchTx)
  205. h.chainSync = newChainSyncer(h)
  206. return h, nil
  207. }
  208. // runEthPeer registers an eth peer into the joint eth/snap peerset, adds it to
  209. // various subsistems and starts handling messages.
  210. func (h *handler) runEthPeer(peer *eth.Peer, handler eth.Handler) error {
  211. // If the peer has a `snap` extension, wait for it to connect so we can have
  212. // a uniform initialization/teardown mechanism
  213. snap, err := h.peers.waitSnapExtension(peer)
  214. if err != nil {
  215. peer.Log().Error("Snapshot extension barrier failed", "err", err)
  216. return err
  217. }
  218. // TODO(karalabe): Not sure why this is needed
  219. if !h.chainSync.handlePeerEvent(peer) {
  220. return p2p.DiscQuitting
  221. }
  222. h.peerWG.Add(1)
  223. defer h.peerWG.Done()
  224. // Execute the Ethereum handshake
  225. var (
  226. genesis = h.chain.Genesis()
  227. head = h.chain.CurrentHeader()
  228. hash = head.Hash()
  229. number = head.Number.Uint64()
  230. td = h.chain.GetTd(hash, number)
  231. )
  232. forkID := forkid.NewID(h.chain.Config(), h.chain.Genesis().Hash(), h.chain.CurrentHeader().Number.Uint64())
  233. if err := peer.Handshake(h.networkID, td, hash, genesis.Hash(), forkID, h.forkFilter); err != nil {
  234. peer.Log().Debug("Ethereum handshake failed", "err", err)
  235. return err
  236. }
  237. reject := false // reserved peer slots
  238. if atomic.LoadUint32(&h.snapSync) == 1 {
  239. if snap == nil {
  240. // If we are running snap-sync, we want to reserve roughly half the peer
  241. // slots for peers supporting the snap protocol.
  242. // The logic here is; we only allow up to 5 more non-snap peers than snap-peers.
  243. if all, snp := h.peers.len(), h.peers.snapLen(); all-snp > snp+5 {
  244. reject = true
  245. }
  246. }
  247. }
  248. // Ignore maxPeers if this is a trusted peer
  249. if !peer.Peer.Info().Network.Trusted {
  250. if reject || h.peers.len() >= h.maxPeers {
  251. return p2p.DiscTooManyPeers
  252. }
  253. }
  254. peer.Log().Debug("Ethereum peer connected", "name", peer.Name())
  255. // Register the peer locally
  256. if err := h.peers.registerPeer(peer, snap); err != nil {
  257. peer.Log().Error("Ethereum peer registration failed", "err", err)
  258. return err
  259. }
  260. defer h.removePeer(peer.ID())
  261. p := h.peers.peer(peer.ID())
  262. if p == nil {
  263. return errors.New("peer dropped during handling")
  264. }
  265. // Register the peer in the downloader. If the downloader considers it banned, we disconnect
  266. if err := h.downloader.RegisterPeer(peer.ID(), peer.Version(), peer); err != nil {
  267. peer.Log().Error("Failed to register peer in eth syncer", "err", err)
  268. return err
  269. }
  270. if snap != nil {
  271. if err := h.downloader.SnapSyncer.Register(snap); err != nil {
  272. peer.Log().Error("Failed to register peer in snap syncer", "err", err)
  273. return err
  274. }
  275. }
  276. h.chainSync.handlePeerEvent(peer)
  277. // Propagate existing transactions. new transactions appearing
  278. // after this will be sent via broadcasts.
  279. h.syncTransactions(peer)
  280. // If we have a trusted CHT, reject all peers below that (avoid fast sync eclipse)
  281. if h.checkpointHash != (common.Hash{}) {
  282. // Request the peer's checkpoint header for chain height/weight validation
  283. if err := peer.RequestHeadersByNumber(h.checkpointNumber, 1, 0, false); err != nil {
  284. return err
  285. }
  286. // Start a timer to disconnect if the peer doesn't reply in time
  287. p.syncDrop = time.AfterFunc(syncChallengeTimeout, func() {
  288. peer.Log().Warn("Checkpoint challenge timed out, dropping", "addr", peer.RemoteAddr(), "type", peer.Name())
  289. h.removePeer(peer.ID())
  290. })
  291. // Make sure it's cleaned up if the peer dies off
  292. defer func() {
  293. if p.syncDrop != nil {
  294. p.syncDrop.Stop()
  295. p.syncDrop = nil
  296. }
  297. }()
  298. }
  299. // If we have any explicit whitelist block hashes, request them
  300. for number := range h.whitelist {
  301. if err := peer.RequestHeadersByNumber(number, 1, 0, false); err != nil {
  302. return err
  303. }
  304. }
  305. // Handle incoming messages until the connection is torn down
  306. return handler(peer)
  307. }
  308. // runSnapExtension registers a `snap` peer into the joint eth/snap peerset and
  309. // starts handling inbound messages. As `snap` is only a satellite protocol to
  310. // `eth`, all subsystem registrations and lifecycle management will be done by
  311. // the main `eth` handler to prevent strange races.
  312. func (h *handler) runSnapExtension(peer *snap.Peer, handler snap.Handler) error {
  313. h.peerWG.Add(1)
  314. defer h.peerWG.Done()
  315. if err := h.peers.registerSnapExtension(peer); err != nil {
  316. peer.Log().Error("Snapshot extension registration failed", "err", err)
  317. return err
  318. }
  319. return handler(peer)
  320. }
  321. // removePeer unregisters a peer from the downloader and fetchers, removes it from
  322. // the set of tracked peers and closes the network connection to it.
  323. func (h *handler) removePeer(id string) {
  324. // Create a custom logger to avoid printing the entire id
  325. var logger log.Logger
  326. if len(id) < 16 {
  327. // Tests use short IDs, don't choke on them
  328. logger = log.New("peer", id)
  329. } else {
  330. logger = log.New("peer", id[:8])
  331. }
  332. // Abort if the peer does not exist
  333. peer := h.peers.peer(id)
  334. if peer == nil {
  335. logger.Error("Ethereum peer removal failed", "err", errPeerNotRegistered)
  336. return
  337. }
  338. // Remove the `eth` peer if it exists
  339. logger.Debug("Removing Ethereum peer", "snap", peer.snapExt != nil)
  340. // Remove the `snap` extension if it exists
  341. if peer.snapExt != nil {
  342. h.downloader.SnapSyncer.Unregister(id)
  343. }
  344. h.downloader.UnregisterPeer(id)
  345. h.txFetcher.Drop(id)
  346. if err := h.peers.unregisterPeer(id); err != nil {
  347. logger.Error("Ethereum peer removal failed", "err", err)
  348. }
  349. // Hard disconnect at the networking layer
  350. peer.Peer.Disconnect(p2p.DiscUselessPeer)
  351. }
  352. func (h *handler) Start(maxPeers int) {
  353. h.maxPeers = maxPeers
  354. // broadcast transactions
  355. h.wg.Add(1)
  356. h.txsCh = make(chan core.NewTxsEvent, txChanSize)
  357. h.txsSub = h.txpool.SubscribeNewTxsEvent(h.txsCh)
  358. go h.txBroadcastLoop()
  359. // broadcast mined blocks
  360. h.wg.Add(1)
  361. h.minedBlockSub = h.eventMux.Subscribe(core.NewMinedBlockEvent{})
  362. go h.minedBroadcastLoop()
  363. // start sync handlers
  364. h.wg.Add(2)
  365. go h.chainSync.loop()
  366. go h.txsyncLoop64() // TODO(karalabe): Legacy initial tx echange, drop with eth/64.
  367. }
  368. func (h *handler) Stop() {
  369. h.txsSub.Unsubscribe() // quits txBroadcastLoop
  370. h.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
  371. // Quit chainSync and txsync64.
  372. // After this is done, no new peers will be accepted.
  373. close(h.quitSync)
  374. h.wg.Wait()
  375. // Disconnect existing sessions.
  376. // This also closes the gate for any new registrations on the peer set.
  377. // sessions which are already established but not added to h.peers yet
  378. // will exit when they try to register.
  379. h.peers.close()
  380. h.peerWG.Wait()
  381. log.Info("Ethereum protocol stopped")
  382. }
  383. // BroadcastBlock will either propagate a block to a subset of its peers, or
  384. // will only announce its availability (depending what's requested).
  385. func (h *handler) BroadcastBlock(block *types.Block, propagate bool) {
  386. hash := block.Hash()
  387. peers := h.peers.peersWithoutBlock(hash)
  388. // If propagation is requested, send to a subset of the peer
  389. if propagate {
  390. // Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
  391. var td *big.Int
  392. if parent := h.chain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
  393. td = new(big.Int).Add(block.Difficulty(), h.chain.GetTd(block.ParentHash(), block.NumberU64()-1))
  394. } else {
  395. log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
  396. return
  397. }
  398. // Send the block to a subset of our peers
  399. transfer := peers[:int(math.Sqrt(float64(len(peers))))]
  400. for _, peer := range transfer {
  401. peer.AsyncSendNewBlock(block, td)
  402. }
  403. log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  404. return
  405. }
  406. // Otherwise if the block is indeed in out own chain, announce it
  407. if h.chain.HasBlock(hash, block.NumberU64()) {
  408. for _, peer := range peers {
  409. peer.AsyncSendNewBlockHash(block)
  410. }
  411. log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  412. }
  413. }
  414. // BroadcastTransactions will propagate a batch of transactions to all peers which are not known to
  415. // already have the given transaction.
  416. func (h *handler) BroadcastTransactions(txs types.Transactions, propagate bool) {
  417. var (
  418. txset = make(map[*ethPeer][]common.Hash)
  419. annos = make(map[*ethPeer][]common.Hash)
  420. )
  421. // Broadcast transactions to a batch of peers not knowing about it
  422. if propagate {
  423. for _, tx := range txs {
  424. peers := h.peers.peersWithoutTransaction(tx.Hash())
  425. // Send the block to a subset of our peers
  426. transfer := peers[:int(math.Sqrt(float64(len(peers))))]
  427. for _, peer := range transfer {
  428. txset[peer] = append(txset[peer], tx.Hash())
  429. }
  430. log.Trace("Broadcast transaction", "hash", tx.Hash(), "recipients", len(transfer))
  431. }
  432. for peer, hashes := range txset {
  433. peer.AsyncSendTransactions(hashes)
  434. }
  435. return
  436. }
  437. // Otherwise only broadcast the announcement to peers
  438. for _, tx := range txs {
  439. peers := h.peers.peersWithoutTransaction(tx.Hash())
  440. for _, peer := range peers {
  441. annos[peer] = append(annos[peer], tx.Hash())
  442. }
  443. }
  444. for peer, hashes := range annos {
  445. if peer.Version() >= eth.ETH65 {
  446. peer.AsyncSendPooledTransactionHashes(hashes)
  447. } else {
  448. peer.AsyncSendTransactions(hashes)
  449. }
  450. }
  451. }
  452. // minedBroadcastLoop sends mined blocks to connected peers.
  453. func (h *handler) minedBroadcastLoop() {
  454. defer h.wg.Done()
  455. for obj := range h.minedBlockSub.Chan() {
  456. if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok {
  457. h.BroadcastBlock(ev.Block, true) // First propagate block to peers
  458. h.BroadcastBlock(ev.Block, false) // Only then announce to the rest
  459. }
  460. }
  461. }
  462. // txBroadcastLoop announces new transactions to connected peers.
  463. func (h *handler) txBroadcastLoop() {
  464. defer h.wg.Done()
  465. for {
  466. select {
  467. case event := <-h.txsCh:
  468. h.BroadcastTransactions(event.Txs, true) // First propagate transactions to peers
  469. h.BroadcastTransactions(event.Txs, false) // Only then announce to the rest
  470. case <-h.txsSub.Err():
  471. return
  472. }
  473. }
  474. }