handler.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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.ethPeer(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
  209. func (h *handler) runEthPeer(peer *eth.Peer, handler eth.Handler) error {
  210. if !h.chainSync.handlePeerEvent(peer) {
  211. return p2p.DiscQuitting
  212. }
  213. h.peerWG.Add(1)
  214. defer h.peerWG.Done()
  215. // Execute the Ethereum handshake
  216. var (
  217. genesis = h.chain.Genesis()
  218. head = h.chain.CurrentHeader()
  219. hash = head.Hash()
  220. number = head.Number.Uint64()
  221. td = h.chain.GetTd(hash, number)
  222. )
  223. forkID := forkid.NewID(h.chain.Config(), h.chain.Genesis().Hash(), h.chain.CurrentHeader().Number.Uint64())
  224. if err := peer.Handshake(h.networkID, td, hash, genesis.Hash(), forkID, h.forkFilter); err != nil {
  225. peer.Log().Debug("Ethereum handshake failed", "err", err)
  226. return err
  227. }
  228. // Ignore maxPeers if this is a trusted peer
  229. if h.peers.Len() >= h.maxPeers && !peer.Peer.Info().Network.Trusted {
  230. return p2p.DiscTooManyPeers
  231. }
  232. peer.Log().Debug("Ethereum peer connected", "name", peer.Name())
  233. // Register the peer locally
  234. if err := h.peers.registerEthPeer(peer); err != nil {
  235. peer.Log().Error("Ethereum peer registration failed", "err", err)
  236. return err
  237. }
  238. defer h.removePeer(peer.ID())
  239. p := h.peers.ethPeer(peer.ID())
  240. if p == nil {
  241. return errors.New("peer dropped during handling")
  242. }
  243. // Register the peer in the downloader. If the downloader considers it banned, we disconnect
  244. if err := h.downloader.RegisterPeer(peer.ID(), peer.Version(), peer); err != nil {
  245. return err
  246. }
  247. h.chainSync.handlePeerEvent(peer)
  248. // Propagate existing transactions. new transactions appearing
  249. // after this will be sent via broadcasts.
  250. h.syncTransactions(peer)
  251. // If we have a trusted CHT, reject all peers below that (avoid fast sync eclipse)
  252. if h.checkpointHash != (common.Hash{}) {
  253. // Request the peer's checkpoint header for chain height/weight validation
  254. if err := peer.RequestHeadersByNumber(h.checkpointNumber, 1, 0, false); err != nil {
  255. return err
  256. }
  257. // Start a timer to disconnect if the peer doesn't reply in time
  258. p.syncDrop = time.AfterFunc(syncChallengeTimeout, func() {
  259. peer.Log().Warn("Checkpoint challenge timed out, dropping", "addr", peer.RemoteAddr(), "type", peer.Name())
  260. h.removePeer(peer.ID())
  261. })
  262. // Make sure it's cleaned up if the peer dies off
  263. defer func() {
  264. if p.syncDrop != nil {
  265. p.syncDrop.Stop()
  266. p.syncDrop = nil
  267. }
  268. }()
  269. }
  270. // If we have any explicit whitelist block hashes, request them
  271. for number := range h.whitelist {
  272. if err := peer.RequestHeadersByNumber(number, 1, 0, false); err != nil {
  273. return err
  274. }
  275. }
  276. // Handle incoming messages until the connection is torn down
  277. return handler(peer)
  278. }
  279. // runSnapPeer
  280. func (h *handler) runSnapPeer(peer *snap.Peer, handler snap.Handler) error {
  281. h.peerWG.Add(1)
  282. defer h.peerWG.Done()
  283. // Register the peer locally
  284. if err := h.peers.registerSnapPeer(peer); err != nil {
  285. peer.Log().Error("Snapshot peer registration failed", "err", err)
  286. return err
  287. }
  288. defer h.removePeer(peer.ID())
  289. if err := h.downloader.SnapSyncer.Register(peer); err != nil {
  290. return err
  291. }
  292. // Handle incoming messages until the connection is torn down
  293. return handler(peer)
  294. }
  295. func (h *handler) removePeer(id string) {
  296. // Remove the eth peer if it exists
  297. eth := h.peers.ethPeer(id)
  298. if eth != nil {
  299. log.Debug("Removing Ethereum peer", "peer", id)
  300. h.downloader.UnregisterPeer(id)
  301. h.txFetcher.Drop(id)
  302. if err := h.peers.unregisterEthPeer(id); err != nil {
  303. log.Error("Peer removal failed", "peer", id, "err", err)
  304. }
  305. }
  306. // Remove the snap peer if it exists
  307. snap := h.peers.snapPeer(id)
  308. if snap != nil {
  309. log.Debug("Removing Snapshot peer", "peer", id)
  310. h.downloader.SnapSyncer.Unregister(id)
  311. if err := h.peers.unregisterSnapPeer(id); err != nil {
  312. log.Error("Peer removal failed", "peer", id, "err", err)
  313. }
  314. }
  315. // Hard disconnect at the networking layer
  316. if eth != nil {
  317. eth.Peer.Disconnect(p2p.DiscUselessPeer)
  318. }
  319. if snap != nil {
  320. snap.Peer.Disconnect(p2p.DiscUselessPeer)
  321. }
  322. }
  323. func (h *handler) Start(maxPeers int) {
  324. h.maxPeers = maxPeers
  325. // broadcast transactions
  326. h.wg.Add(1)
  327. h.txsCh = make(chan core.NewTxsEvent, txChanSize)
  328. h.txsSub = h.txpool.SubscribeNewTxsEvent(h.txsCh)
  329. go h.txBroadcastLoop()
  330. // broadcast mined blocks
  331. h.wg.Add(1)
  332. h.minedBlockSub = h.eventMux.Subscribe(core.NewMinedBlockEvent{})
  333. go h.minedBroadcastLoop()
  334. // start sync handlers
  335. h.wg.Add(2)
  336. go h.chainSync.loop()
  337. go h.txsyncLoop64() // TODO(karalabe): Legacy initial tx echange, drop with eth/64.
  338. }
  339. func (h *handler) Stop() {
  340. h.txsSub.Unsubscribe() // quits txBroadcastLoop
  341. h.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
  342. // Quit chainSync and txsync64.
  343. // After this is done, no new peers will be accepted.
  344. close(h.quitSync)
  345. h.wg.Wait()
  346. // Disconnect existing sessions.
  347. // This also closes the gate for any new registrations on the peer set.
  348. // sessions which are already established but not added to h.peers yet
  349. // will exit when they try to register.
  350. h.peers.close()
  351. h.peerWG.Wait()
  352. log.Info("Ethereum protocol stopped")
  353. }
  354. // BroadcastBlock will either propagate a block to a subset of its peers, or
  355. // will only announce its availability (depending what's requested).
  356. func (h *handler) BroadcastBlock(block *types.Block, propagate bool) {
  357. hash := block.Hash()
  358. peers := h.peers.ethPeersWithoutBlock(hash)
  359. // If propagation is requested, send to a subset of the peer
  360. if propagate {
  361. // Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
  362. var td *big.Int
  363. if parent := h.chain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
  364. td = new(big.Int).Add(block.Difficulty(), h.chain.GetTd(block.ParentHash(), block.NumberU64()-1))
  365. } else {
  366. log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
  367. return
  368. }
  369. // Send the block to a subset of our peers
  370. transfer := peers[:int(math.Sqrt(float64(len(peers))))]
  371. for _, peer := range transfer {
  372. peer.AsyncSendNewBlock(block, td)
  373. }
  374. log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  375. return
  376. }
  377. // Otherwise if the block is indeed in out own chain, announce it
  378. if h.chain.HasBlock(hash, block.NumberU64()) {
  379. for _, peer := range peers {
  380. peer.AsyncSendNewBlockHash(block)
  381. }
  382. log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  383. }
  384. }
  385. // BroadcastTransactions will propagate a batch of transactions to all peers which are not known to
  386. // already have the given transaction.
  387. func (h *handler) BroadcastTransactions(txs types.Transactions, propagate bool) {
  388. var (
  389. txset = make(map[*ethPeer][]common.Hash)
  390. annos = make(map[*ethPeer][]common.Hash)
  391. )
  392. // Broadcast transactions to a batch of peers not knowing about it
  393. if propagate {
  394. for _, tx := range txs {
  395. peers := h.peers.ethPeersWithoutTransaction(tx.Hash())
  396. // Send the block to a subset of our peers
  397. transfer := peers[:int(math.Sqrt(float64(len(peers))))]
  398. for _, peer := range transfer {
  399. txset[peer] = append(txset[peer], tx.Hash())
  400. }
  401. log.Trace("Broadcast transaction", "hash", tx.Hash(), "recipients", len(transfer))
  402. }
  403. for peer, hashes := range txset {
  404. peer.AsyncSendTransactions(hashes)
  405. }
  406. return
  407. }
  408. // Otherwise only broadcast the announcement to peers
  409. for _, tx := range txs {
  410. peers := h.peers.ethPeersWithoutTransaction(tx.Hash())
  411. for _, peer := range peers {
  412. annos[peer] = append(annos[peer], tx.Hash())
  413. }
  414. }
  415. for peer, hashes := range annos {
  416. if peer.Version() >= eth.ETH65 {
  417. peer.AsyncSendPooledTransactionHashes(hashes)
  418. } else {
  419. peer.AsyncSendTransactions(hashes)
  420. }
  421. }
  422. }
  423. // minedBroadcastLoop sends mined blocks to connected peers.
  424. func (h *handler) minedBroadcastLoop() {
  425. defer h.wg.Done()
  426. for obj := range h.minedBlockSub.Chan() {
  427. if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok {
  428. h.BroadcastBlock(ev.Block, true) // First propagate block to peers
  429. h.BroadcastBlock(ev.Block, false) // Only then announce to the rest
  430. }
  431. }
  432. }
  433. // txBroadcastLoop announces new transactions to connected peers.
  434. func (h *handler) txBroadcastLoop() {
  435. defer h.wg.Done()
  436. for {
  437. select {
  438. case event := <-h.txsCh:
  439. h.BroadcastTransactions(event.Txs, true) // First propagate transactions to peers
  440. h.BroadcastTransactions(event.Txs, false) // Only then announce to the rest
  441. case <-h.txsSub.Err():
  442. return
  443. }
  444. }
  445. }