handler.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  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. "fmt"
  20. "math"
  21. "math/big"
  22. "sync"
  23. "sync/atomic"
  24. "time"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/consensus"
  27. "github.com/ethereum/go-ethereum/consensus/clique"
  28. "github.com/ethereum/go-ethereum/consensus/ethash"
  29. "github.com/ethereum/go-ethereum/consensus/istanbul"
  30. "github.com/ethereum/go-ethereum/core"
  31. "github.com/ethereum/go-ethereum/core/forkid"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/crypto"
  34. "github.com/ethereum/go-ethereum/eth/downloader"
  35. "github.com/ethereum/go-ethereum/eth/fetcher"
  36. "github.com/ethereum/go-ethereum/eth/protocols/eth"
  37. "github.com/ethereum/go-ethereum/eth/protocols/snap"
  38. "github.com/ethereum/go-ethereum/ethdb"
  39. "github.com/ethereum/go-ethereum/event"
  40. "github.com/ethereum/go-ethereum/log"
  41. "github.com/ethereum/go-ethereum/p2p"
  42. "github.com/ethereum/go-ethereum/p2p/enode"
  43. "github.com/ethereum/go-ethereum/p2p/enr"
  44. "github.com/ethereum/go-ethereum/params"
  45. "github.com/ethereum/go-ethereum/qlight"
  46. "github.com/ethereum/go-ethereum/trie"
  47. )
  48. const (
  49. // txChanSize is the size of channel listening to NewTxsEvent.
  50. // The number is referenced from the size of tx pool.
  51. txChanSize = 4096
  52. // Quorum
  53. protocolMaxMsgSize = 10 * 1024 * 1024 // Maximum cap on the size of a protocol message
  54. )
  55. var (
  56. syncChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the sync progress challenge
  57. // Quorum
  58. errMsgTooLarge = errors.New("message too long")
  59. )
  60. // txPool defines the methods needed from a transaction pool implementation to
  61. // support all the operations needed by the Ethereum chain protocols.
  62. type txPool interface {
  63. // Has returns an indicator whether txpool has a transaction
  64. // cached with the given hash.
  65. Has(hash common.Hash) bool
  66. // Get retrieves the transaction from local txpool with given
  67. // tx hash.
  68. Get(hash common.Hash) *types.Transaction
  69. // AddRemotes should add the given transactions to the pool.
  70. AddRemotes([]*types.Transaction) []error
  71. // Pending should return pending transactions.
  72. // The slice should be modifiable by the caller.
  73. Pending() (map[common.Address]types.Transactions, error)
  74. // SubscribeNewTxsEvent should return an event subscription of
  75. // NewTxsEvent and send events to the given channel.
  76. SubscribeNewTxsEvent(chan<- core.NewTxsEvent) event.Subscription
  77. }
  78. // handlerConfig is the collection of initialization parameters to create a full
  79. // node network handler.
  80. type handlerConfig struct {
  81. Database ethdb.Database // Database for direct sync insertions
  82. Chain *core.BlockChain // Blockchain to serve data from
  83. TxPool txPool // Transaction pool to propagate from
  84. Network uint64 // Network identifier to adfvertise
  85. Sync downloader.SyncMode // Whether to fast or full sync
  86. BloomCache uint64 // Megabytes to alloc for fast sync bloom
  87. EventMux *event.TypeMux // Legacy event mux, deprecate for `feed`
  88. Checkpoint *params.TrustedCheckpoint // Hard coded checkpoint for sync challenges
  89. // Quorum
  90. AuthorizationList map[uint64]common.Hash // Hard coded authorization list for sync challenged
  91. Engine consensus.Engine
  92. RaftMode bool
  93. // Quorum QLight
  94. // client
  95. psi string
  96. privateClientCache qlight.PrivateClientCache
  97. tokenHolder *qlight.TokenHolder
  98. // server
  99. authProvider qlight.AuthProvider
  100. privateBlockDataResolver qlight.PrivateBlockDataResolver
  101. }
  102. type handler struct {
  103. networkID uint64
  104. forkFilter forkid.Filter // Fork ID filter, constant across the lifetime of the node
  105. fastSync uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks)
  106. snapSync uint32 // Flag whether fast sync should operate on top of the snap protocol
  107. acceptTxs uint32 // Flag whether we're considered synchronised (enables transaction processing)
  108. checkpointNumber uint64 // Block number for the sync progress validator to cross reference
  109. checkpointHash common.Hash // Block hash for the sync progress validator to cross reference
  110. database ethdb.Database
  111. txpool txPool
  112. chain *core.BlockChain
  113. maxPeers int
  114. downloader *downloader.Downloader
  115. stateBloom *trie.SyncBloom
  116. blockFetcher *fetcher.BlockFetcher
  117. txFetcher *fetcher.TxFetcher
  118. peers *peerSet
  119. eventMux *event.TypeMux
  120. txsCh chan core.NewTxsEvent
  121. txsSub event.Subscription
  122. minedBlockSub *event.TypeMuxSubscription
  123. authorizationList map[uint64]common.Hash
  124. // channels for fetcher, syncer, txsyncLoop
  125. txsyncCh chan *txsync
  126. quitSync chan struct{}
  127. chainSync *chainSyncer
  128. wg sync.WaitGroup
  129. peerWG sync.WaitGroup
  130. // Quorum
  131. raftMode bool
  132. engine consensus.Engine
  133. tokenHolder *qlight.TokenHolder
  134. // Test fields or hooks
  135. broadcastTxAnnouncesOnly bool // Testing field, disable transaction propagation
  136. // Quorum QLight
  137. // client
  138. psi string
  139. privateClientCache qlight.PrivateClientCache
  140. // server
  141. authProvider qlight.AuthProvider
  142. privateBlockDataResolver qlight.PrivateBlockDataResolver
  143. }
  144. // newHandler returns a handler for all Ethereum chain management protocol.
  145. func newHandler(config *handlerConfig) (*handler, error) {
  146. // Create the protocol manager with the base fields
  147. if config.EventMux == nil {
  148. config.EventMux = new(event.TypeMux) // Nicety initialization for tests
  149. }
  150. h := &handler{
  151. networkID: config.Network,
  152. forkFilter: forkid.NewFilter(config.Chain),
  153. eventMux: config.EventMux,
  154. database: config.Database,
  155. txpool: config.TxPool,
  156. chain: config.Chain,
  157. peers: newPeerSet(),
  158. txsyncCh: make(chan *txsync),
  159. quitSync: make(chan struct{}),
  160. // Quorum
  161. authorizationList: config.AuthorizationList,
  162. raftMode: config.RaftMode,
  163. engine: config.Engine,
  164. tokenHolder: config.tokenHolder,
  165. }
  166. // Quorum
  167. if handler, ok := h.engine.(consensus.Handler); ok {
  168. handler.SetBroadcaster(h)
  169. }
  170. // /Quorum
  171. if config.Sync == downloader.FullSync {
  172. // The database seems empty as the current block is the genesis. Yet the fast
  173. // block is ahead, so fast sync was enabled for this node at a certain point.
  174. // The scenarios where this can happen is
  175. // * if the user manually (or via a bad block) rolled back a fast sync node
  176. // below the sync point.
  177. // * the last fast sync is not finished while user specifies a full sync this
  178. // time. But we don't have any recent state for full sync.
  179. // In these cases however it's safe to reenable fast sync.
  180. fullBlock, fastBlock := h.chain.CurrentBlock(), h.chain.CurrentFastBlock()
  181. if fullBlock.NumberU64() == 0 && fastBlock.NumberU64() > 0 {
  182. h.fastSync = uint32(1)
  183. log.Warn("Switch sync mode from full sync to fast sync")
  184. }
  185. } else {
  186. if h.chain.CurrentBlock().NumberU64() > 0 {
  187. // Print warning log if database is not empty to run fast sync.
  188. log.Warn("Switch sync mode from fast sync to full sync")
  189. } else {
  190. // If fast sync was requested and our database is empty, grant it
  191. h.fastSync = uint32(1)
  192. if config.Sync == downloader.SnapSync {
  193. h.snapSync = uint32(1)
  194. }
  195. }
  196. }
  197. // If we have trusted checkpoints, enforce them on the chain
  198. if config.Checkpoint != nil {
  199. h.checkpointNumber = (config.Checkpoint.SectionIndex+1)*params.CHTFrequency - 1
  200. h.checkpointHash = config.Checkpoint.SectionHead
  201. }
  202. // Construct the downloader (long sync) and its backing state bloom if fast
  203. // sync is requested. The downloader is responsible for deallocating the state
  204. // bloom when it's done.
  205. // Note: we don't enable it if snap-sync is performed, since it's very heavy
  206. // and the heal-portion of the snap sync is much lighter than fast. What we particularly
  207. // want to avoid, is a 90%-finished (but restarted) snap-sync to begin
  208. // indexing the entire trie
  209. if atomic.LoadUint32(&h.fastSync) == 1 && atomic.LoadUint32(&h.snapSync) == 0 {
  210. h.stateBloom = trie.NewSyncBloom(config.BloomCache, config.Database)
  211. }
  212. h.downloader = downloader.New(h.checkpointNumber, config.Database, h.stateBloom, h.eventMux, h.chain, nil, h.removePeer)
  213. // Construct the fetcher (short sync)
  214. validator := func(header *types.Header) error {
  215. return h.chain.Engine().VerifyHeader(h.chain, header, true)
  216. }
  217. heighter := func() uint64 {
  218. return h.chain.CurrentBlock().NumberU64()
  219. }
  220. inserter := func(blocks types.Blocks) (int, error) {
  221. // If sync hasn't reached the checkpoint yet, deny importing weird blocks.
  222. //
  223. // Ideally we would also compare the head block's timestamp and similarly reject
  224. // the propagated block if the head is too old. Unfortunately there is a corner
  225. // case when starting new networks, where the genesis might be ancient (0 unix)
  226. // which would prevent full nodes from accepting it.
  227. if h.chain.CurrentBlock().NumberU64() < h.checkpointNumber {
  228. log.Warn("Unsynced yet, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
  229. return 0, nil
  230. }
  231. // If fast sync is running, deny importing weird blocks. This is a problematic
  232. // clause when starting up a new network, because fast-syncing miners might not
  233. // accept each others' blocks until a restart. Unfortunately we haven't figured
  234. // out a way yet where nodes can decide unilaterally whether the network is new
  235. // or not. This should be fixed if we figure out a solution.
  236. if atomic.LoadUint32(&h.fastSync) == 1 {
  237. log.Warn("Fast syncing, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
  238. return 0, nil
  239. }
  240. n, err := h.chain.InsertChain(blocks)
  241. if err == nil {
  242. atomic.StoreUint32(&h.acceptTxs, 1) // Mark initial sync done on any fetcher import
  243. }
  244. return n, err
  245. }
  246. h.blockFetcher = fetcher.NewBlockFetcher(false, nil, h.chain.GetBlockByHash, validator, h.BroadcastBlock, heighter, nil, inserter, h.removePeer)
  247. fetchTx := func(peer string, hashes []common.Hash) error {
  248. p := h.peers.peer(peer)
  249. if p == nil {
  250. return errors.New("unknown peer")
  251. }
  252. return p.RequestTxs(hashes)
  253. }
  254. h.txFetcher = fetcher.NewTxFetcher(h.txpool.Has, h.txpool.AddRemotes, fetchTx)
  255. h.chainSync = newChainSyncer(h)
  256. return h, nil
  257. }
  258. // runEthPeer registers an eth peer into the joint eth/snap peerset, adds it to
  259. // various subsistems and starts handling messages.
  260. func (h *handler) runEthPeer(peer *eth.Peer, handler eth.Handler) error {
  261. // If the peer has a `snap` extension, wait for it to connect so we can have
  262. // a uniform initialization/teardown mechanism
  263. snap, err := h.peers.waitSnapExtension(peer)
  264. if err != nil {
  265. peer.Log().Error("Snapshot extension barrier failed", "err", err)
  266. return err
  267. }
  268. // TODO(karalabe): Not sure why this is needed
  269. if !h.chainSync.handlePeerEvent(peer) {
  270. return p2p.DiscQuitting
  271. }
  272. h.peerWG.Add(1)
  273. defer h.peerWG.Done()
  274. // Execute the Ethereum handshake
  275. var (
  276. genesis = h.chain.Genesis()
  277. head = h.chain.CurrentHeader()
  278. hash = head.Hash()
  279. number = head.Number.Uint64()
  280. td = h.chain.GetTd(hash, number)
  281. )
  282. forkID := forkid.NewID(h.chain.Config(), h.chain.Genesis().Hash(), h.chain.CurrentHeader().Number.Uint64())
  283. if err := peer.Handshake(h.networkID, td, hash, genesis.Hash(), forkID, h.forkFilter); err != nil {
  284. peer.Log().Debug("Ethereum handshake failed", "err", err)
  285. // Quorum
  286. // When the Handshake() returns an error, the Run method corresponding to `eth` protocol returns with the error, causing the peer to drop, signal subprotocol as well to exit the `Run` method
  287. peer.EthPeerDisconnected <- struct{}{}
  288. // End Quorum
  289. return err
  290. }
  291. reject := false // reserved peer slots
  292. if atomic.LoadUint32(&h.snapSync) == 1 {
  293. if snap == nil {
  294. // If we are running snap-sync, we want to reserve roughly half the peer
  295. // slots for peers supporting the snap protocol.
  296. // The logic here is; we only allow up to 5 more non-snap peers than snap-peers.
  297. if all, snp := h.peers.len(), h.peers.snapLen(); all-snp > snp+5 {
  298. reject = true
  299. }
  300. }
  301. }
  302. // Ignore maxPeers if this is a trusted peer
  303. if !peer.Peer.Info().Network.Trusted {
  304. if reject || h.peers.len() >= h.maxPeers {
  305. return p2p.DiscTooManyPeers
  306. }
  307. }
  308. peer.Log().Debug("Ethereum peer connected", "name", peer.Name())
  309. // Register the peer locally
  310. if err := h.peers.registerPeer(peer, snap); err != nil {
  311. peer.Log().Error("Ethereum peer registration failed", "err", err)
  312. // Quorum
  313. // When the Register() returns an error, the Run method corresponding to `eth` protocol returns with the error, causing the peer to drop, signal subprotocol as well to exit the `Run` method
  314. peer.EthPeerDisconnected <- struct{}{}
  315. // End Quorum
  316. return err
  317. }
  318. defer h.unregisterPeer(peer.ID()) // Quorum: changed by https://github.com/bnb-chain/bsc/pull/856
  319. p := h.peers.peer(peer.ID())
  320. if p == nil {
  321. return errors.New("peer dropped during handling")
  322. }
  323. // Register the peer in the downloader. If the downloader considers it banned, we disconnect
  324. if err := h.downloader.RegisterPeer(peer.ID(), peer.Version(), peer); err != nil {
  325. peer.Log().Error("Failed to register peer in eth syncer", "err", err)
  326. return err
  327. }
  328. if snap != nil {
  329. if err := h.downloader.SnapSyncer.Register(snap); err != nil {
  330. peer.Log().Error("Failed to register peer in snap syncer", "err", err)
  331. return err
  332. }
  333. }
  334. h.chainSync.handlePeerEvent(peer)
  335. // Propagate existing transactions. new transactions appearing
  336. // after this will be sent via broadcasts.
  337. h.syncTransactions(peer)
  338. // If we have a trusted CHT, reject all peers below that (avoid fast sync eclipse)
  339. if h.checkpointHash != (common.Hash{}) {
  340. // Request the peer's checkpoint header for chain height/weight validation
  341. if err := peer.RequestHeadersByNumber(h.checkpointNumber, 1, 0, false); err != nil {
  342. return err
  343. }
  344. // Start a timer to disconnect if the peer doesn't reply in time
  345. p.syncDrop = time.AfterFunc(syncChallengeTimeout, func() {
  346. peer.Log().Warn("Checkpoint challenge timed out, dropping", "addr", peer.RemoteAddr(), "type", peer.Name())
  347. h.removePeer(peer.ID())
  348. })
  349. // Make sure it's cleaned up if the peer dies off
  350. defer func() {
  351. if p.syncDrop != nil {
  352. p.syncDrop.Stop()
  353. p.syncDrop = nil
  354. }
  355. }()
  356. }
  357. // If we have any explicit authorized block hashes, request them
  358. for number := range h.authorizationList {
  359. if err := peer.RequestHeadersByNumber(number, 1, 0, false); err != nil {
  360. return err
  361. }
  362. }
  363. // Quorum notify other subprotocols that the eth peer is ready, and has been added to the peerset.
  364. p.EthPeerRegistered <- struct{}{}
  365. // Quorum
  366. // Handle incoming messages until the connection is torn down
  367. return handler(peer)
  368. }
  369. // runSnapExtension registers a `snap` peer into the joint eth/snap peerset and
  370. // starts handling inbound messages. As `snap` is only a satellite protocol to
  371. // `eth`, all subsystem registrations and lifecycle management will be done by
  372. // the main `eth` handler to prevent strange races.
  373. func (h *handler) runSnapExtension(peer *snap.Peer, handler snap.Handler) error {
  374. h.peerWG.Add(1)
  375. defer h.peerWG.Done()
  376. if err := h.peers.registerSnapExtension(peer); err != nil {
  377. peer.Log().Error("Snapshot extension registration failed", "err", err)
  378. return err
  379. }
  380. return handler(peer)
  381. }
  382. // removePeer requests disconnection of a peer.
  383. // Quorum: added by https://github.com/bnb-chain/bsc/pull/856
  384. func (h *handler) removePeer(id string) {
  385. peer := h.peers.peer(id)
  386. if peer != nil {
  387. // Hard disconnect at the networking layer. Handler will get an EOF and terminate the peer. defer unregisterPeer will do the cleanup task after then.
  388. peer.Peer.Disconnect(p2p.DiscUselessPeer)
  389. }
  390. }
  391. // unregisterPeer removes a peer from the downloader, fetchers and main peer set.
  392. // Quorum: changed by https://github.com/bnb-chain/bsc/pull/856
  393. func (h *handler) unregisterPeer(id string) {
  394. // Create a custom logger to avoid printing the entire id
  395. var logger log.Logger
  396. if len(id) < 16 {
  397. // Tests use short IDs, don't choke on them
  398. logger = log.New("peer", id)
  399. } else {
  400. logger = log.New("peer", id[:8])
  401. }
  402. // Abort if the peer does not exist
  403. peer := h.peers.peer(id)
  404. if peer == nil {
  405. logger.Error("Ethereum peer removal failed", "err", errPeerNotRegistered)
  406. return
  407. }
  408. // Remove the `eth` peer if it exists
  409. logger.Debug("Removing Ethereum peer", "snap", peer.snapExt != nil)
  410. // Remove the `snap` extension if it exists
  411. if peer.snapExt != nil {
  412. h.downloader.SnapSyncer.Unregister(id)
  413. }
  414. h.downloader.UnregisterPeer(id)
  415. h.txFetcher.Drop(id)
  416. if err := h.peers.unregisterPeer(id); err != nil {
  417. logger.Error("Ethereum peer removal failed", "err", err)
  418. }
  419. // Hard disconnect at the networking layer
  420. // peer.Peer.Disconnect(p2p.DiscUselessPeer) // Quorum: removed by https://github.com/bnb-chain/bsc/pull/856
  421. }
  422. func (h *handler) Start(maxPeers int) {
  423. h.maxPeers = maxPeers
  424. // broadcast transactions
  425. h.wg.Add(1)
  426. h.txsCh = make(chan core.NewTxsEvent, txChanSize)
  427. h.txsSub = h.txpool.SubscribeNewTxsEvent(h.txsCh)
  428. go h.txBroadcastLoop()
  429. // Quorum
  430. if !h.raftMode {
  431. // broadcast mined blocks
  432. h.wg.Add(1)
  433. h.minedBlockSub = h.eventMux.Subscribe(core.NewMinedBlockEvent{})
  434. go h.minedBroadcastLoop()
  435. } else {
  436. // We set this immediately in raft mode to make sure the miner never drops
  437. // incoming txes. Raft mode doesn't use the fetcher or downloader, and so
  438. // this would never be set otherwise.
  439. atomic.StoreUint32(&h.acceptTxs, 1)
  440. }
  441. // End Quorum
  442. // start sync handlers
  443. h.wg.Add(2)
  444. go h.chainSync.loop()
  445. go h.txsyncLoop64() // TODO(karalabe): Legacy initial tx echange, drop with eth/64.
  446. }
  447. func (h *handler) Stop() {
  448. h.txsSub.Unsubscribe() // quits txBroadcastLoop
  449. // quorum - ensure raft stops cleanly
  450. if h.minedBlockSub != nil {
  451. h.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
  452. }
  453. // Quit chainSync and txsync64.
  454. // After this is done, no new peers will be accepted.
  455. close(h.quitSync)
  456. h.wg.Wait()
  457. // Disconnect existing sessions.
  458. // This also closes the gate for any new registrations on the peer set.
  459. // sessions which are already established but not added to h.peers yet
  460. // will exit when they try to register.
  461. h.peers.close()
  462. h.peerWG.Wait()
  463. log.Info("Ethereum protocol stopped")
  464. }
  465. // Quorum
  466. func (h *handler) Enqueue(id string, block *types.Block) {
  467. h.blockFetcher.Enqueue(id, block)
  468. }
  469. // BroadcastBlock will either propagate a block to a subset of its peers, or
  470. // will only announce its availability (depending what's requested).
  471. func (h *handler) BroadcastBlock(block *types.Block, propagate bool) {
  472. hash := block.Hash()
  473. peers := h.peers.peersWithoutBlock(hash)
  474. // If propagation is requested, send to a subset of the peer
  475. if propagate {
  476. // Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
  477. var td *big.Int
  478. if parent := h.chain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
  479. td = new(big.Int).Add(block.Difficulty(), h.chain.GetTd(block.ParentHash(), block.NumberU64()-1))
  480. } else {
  481. log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
  482. return
  483. }
  484. // Send the block to a subset of our peers
  485. transfer := peers[:int(math.Sqrt(float64(len(peers))))]
  486. for _, peer := range transfer {
  487. peer.AsyncSendNewBlock(block, td)
  488. }
  489. log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  490. return
  491. }
  492. // Otherwise if the block is indeed in out own chain, announce it
  493. if h.chain.HasBlock(hash, block.NumberU64()) {
  494. for _, peer := range peers {
  495. peer.AsyncSendNewBlockHash(block)
  496. }
  497. log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
  498. }
  499. }
  500. // BroadcastTransactions will propagate a batch of transactions
  501. // - To a square root of all peers
  502. // - And, separately, as announcements to all peers which are not known to
  503. // already have the given transaction.
  504. func (h *handler) BroadcastTransactions(txs types.Transactions) {
  505. var (
  506. annoCount int // Count of announcements made
  507. annoPeers int
  508. directCount int // Count of the txs sent directly to peers
  509. directPeers int // Count of the peers that were sent transactions directly
  510. txset = make(map[*ethPeer][]common.Hash) // Set peer->hash to transfer directly
  511. annos = make(map[*ethPeer][]common.Hash) // Set peer->hash to announce
  512. )
  513. // Broadcast transactions to a batch of peers not knowing about it
  514. // NOTE: Raft-based consensus currently assumes that geth broadcasts
  515. // transactions to all peers in the network. A previous comment here
  516. // indicated that this logic might change in the future to only send to a
  517. // subset of peers. If this change occurs upstream, a merge conflict should
  518. // arise here, and we should add logic to send to *all* peers in raft mode.
  519. for _, tx := range txs {
  520. peers := h.peers.peersWithoutTransaction(tx.Hash())
  521. // Send the tx unconditionally to a subset of our peers
  522. // Quorum changes for broadcasting to all peers not only Sqrt
  523. //numDirect := int(math.Sqrt(float64(len(peers))))
  524. for _, peer := range peers {
  525. txset[peer] = append(txset[peer], tx.Hash())
  526. }
  527. // For the remaining peers, send announcement only
  528. //for _, peer := range peers[numDirect:] {
  529. // annos[peer] = append(annos[peer], tx.Hash())
  530. //}
  531. log.Trace("Broadcast transaction", "hash", tx.Hash(), "recipients", len(peers))
  532. }
  533. for peer, hashes := range txset {
  534. directPeers++
  535. directCount += len(hashes)
  536. peer.AsyncSendTransactions(hashes)
  537. }
  538. for peer, hashes := range txset {
  539. directPeers++
  540. directCount += len(hashes)
  541. peer.AsyncSendTransactions(hashes)
  542. }
  543. for peer, hashes := range annos {
  544. annoPeers++
  545. annoCount += len(hashes)
  546. peer.AsyncSendPooledTransactionHashes(hashes)
  547. }
  548. log.Debug("Transaction broadcast", "txs", len(txs),
  549. "announce packs", annoPeers, "announced hashes", annoCount,
  550. "tx packs", directPeers, "broadcast txs", directCount)
  551. }
  552. // minedBroadcastLoop sends mined blocks to connected peers.
  553. func (h *handler) minedBroadcastLoop() {
  554. defer h.wg.Done()
  555. for obj := range h.minedBlockSub.Chan() {
  556. if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok {
  557. h.BroadcastBlock(ev.Block, true) // First propagate block to peers
  558. h.BroadcastBlock(ev.Block, false) // Only then announce to the rest
  559. }
  560. }
  561. }
  562. // txBroadcastLoop announces new transactions to connected peers.
  563. func (h *handler) txBroadcastLoop() {
  564. defer h.wg.Done()
  565. for {
  566. select {
  567. case event := <-h.txsCh:
  568. h.BroadcastTransactions(event.Txs)
  569. case <-h.txsSub.Err():
  570. return
  571. }
  572. }
  573. }
  574. // NodeInfo represents a short summary of the Ethereum sub-protocol metadata
  575. // known about the host peer.
  576. type NodeInfo struct {
  577. Network uint64 `json:"network"` // Ethereum network ID (1=Frontier, 2=Morden, Ropsten=3, Rinkeby=4)
  578. Difficulty *big.Int `json:"difficulty"` // Total difficulty of the host's blockchain
  579. Genesis common.Hash `json:"genesis"` // SHA3 hash of the host's genesis block
  580. Config *params.ChainConfig `json:"config"` // Chain configuration for the fork rules
  581. Head common.Hash `json:"head"` // SHA3 hash of the host's best owned block
  582. Consensus string `json:"consensus"` // Consensus mechanism in use
  583. }
  584. // NodeInfo retrieves some protocol metadata about the running host node.
  585. func (h *handler) NodeInfo() *NodeInfo {
  586. currentBlock := h.chain.CurrentBlock()
  587. // //Quorum
  588. //
  589. // changes done to fetch maxCodeSize dynamically based on the
  590. // maxCodeSizeConfig changes
  591. // /Quorum
  592. chainConfig := h.chain.Config()
  593. chainConfig.MaxCodeSize = uint64(chainConfig.GetMaxCodeSize(h.chain.CurrentBlock().Number()) / 1024)
  594. return &NodeInfo{
  595. Network: h.networkID,
  596. Difficulty: h.chain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()),
  597. Genesis: h.chain.Genesis().Hash(),
  598. Config: chainConfig,
  599. Head: currentBlock.Hash(),
  600. Consensus: h.getConsensusAlgorithm(),
  601. }
  602. }
  603. // Quorum
  604. func (h *handler) getConsensusAlgorithm() string {
  605. var consensusAlgo string
  606. if h.raftMode { // raft does not use consensus interface
  607. consensusAlgo = "raft"
  608. } else {
  609. switch h.engine.(type) {
  610. case consensus.Istanbul:
  611. consensusAlgo = "istanbul"
  612. case *clique.Clique:
  613. consensusAlgo = "clique"
  614. case *ethash.Ethash:
  615. consensusAlgo = "ethash"
  616. default:
  617. consensusAlgo = "unknown"
  618. }
  619. }
  620. return consensusAlgo
  621. }
  622. func (h *handler) FindPeers(targets map[common.Address]bool) map[common.Address]consensus.Peer {
  623. m := make(map[common.Address]consensus.Peer)
  624. h.peers.lock.RLock()
  625. defer h.peers.lock.RUnlock()
  626. for _, p := range h.peers.peers {
  627. pubKey := p.Node().Pubkey()
  628. addr := crypto.PubkeyToAddress(*pubKey)
  629. if targets[addr] {
  630. m[addr] = p
  631. }
  632. }
  633. return m
  634. }
  635. // makeQuorumConsensusProtocol is similar to eth/handler.go -> makeProtocol. Called from eth/handler.go -> Protocols.
  636. // returns the supported subprotocol to the p2p server.
  637. // The Run method starts the protocol and is called by the p2p server. The quorum consensus subprotocol,
  638. // leverages the peer created and managed by the "eth" subprotocol.
  639. // The quorum consensus protocol requires that the "eth" protocol is running as well.
  640. func (h *handler) makeQuorumConsensusProtocol(protoName string, version uint, length uint64, backend eth.Backend, network uint64, dnsdisc enode.Iterator) p2p.Protocol {
  641. log.Debug("registering qouorum protocol ", "protoName", protoName, "version", version)
  642. return p2p.Protocol{
  643. Name: protoName,
  644. Version: version,
  645. Length: length,
  646. // no new peer created, uses the "eth" peer, so no peer management needed.
  647. Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  648. /*
  649. * 1. wait for the eth protocol to create and register an eth peer.
  650. * 2. get the associate eth peer that was registered by he "eth" protocol.
  651. * 3. add the rw protocol for the quorum subprotocol to the eth peer.
  652. * 4. start listening for incoming messages.
  653. * 5. the incoming message will be sent on the quorum specific subprotocol, e.g. "istanbul/100".
  654. * 6. send messages to the consensus engine handler.
  655. * 7. messages to other to other peers listening to the subprotocol can be sent using the
  656. * (eth)peer.ConsensusSend() which will write to the protoRW.
  657. */
  658. // wait for the "eth" protocol to create and register the peer (added to peerset)
  659. select {
  660. case <-p.EthPeerRegistered:
  661. // the ethpeer should be registered, try to retrieve it and start the consensus handler.
  662. p2pPeerId := fmt.Sprintf("%x", p.ID().Bytes()[:8])
  663. ethPeer := h.peers.peer(p2pPeerId)
  664. if ethPeer == nil {
  665. p2pPeerId = fmt.Sprintf("%x", p.ID().Bytes()) //TODO:BBO
  666. ethPeer = h.peers.peer(p2pPeerId)
  667. log.Warn("full p2p peer", "id", p2pPeerId, "ethPeer", ethPeer)
  668. }
  669. if ethPeer != nil {
  670. p.Log().Debug("consensus subprotocol retrieved eth peer from peerset", "ethPeer.id", p2pPeerId, "ProtoName", protoName)
  671. // add the rw protocol for the quorum subprotocol to the eth peer.
  672. ethPeer.AddConsensusProtoRW(rw)
  673. peer := eth.NewPeer(version, p, rw, h.txpool)
  674. return h.handleConsensusLoop(peer, rw, nil)
  675. }
  676. p.Log().Error("consensus subprotocol retrieved nil eth peer from peerset", "ethPeer.id", p2pPeerId)
  677. return errEthPeerNil
  678. case <-p.EthPeerDisconnected:
  679. return errEthPeerNotRegistered
  680. }
  681. },
  682. NodeInfo: func() interface{} {
  683. return eth.NodeInfoFunc(backend.Chain(), network)
  684. },
  685. PeerInfo: func(id enode.ID) interface{} {
  686. return backend.PeerInfo(id)
  687. },
  688. Attributes: []enr.Entry{eth.CurrentENREntry(backend.Chain())},
  689. DialCandidates: dnsdisc,
  690. }
  691. }
  692. func (h *handler) handleConsensusLoop(p *eth.Peer, protoRW p2p.MsgReadWriter, fallThroughBackend eth.Backend) error {
  693. // Handle incoming messages until the connection is torn down
  694. for {
  695. if err := h.handleConsensus(p, protoRW, fallThroughBackend); err != nil {
  696. // allow the P2P connection to remain active during sync (when the engine is stopped)
  697. if errors.Is(err, istanbul.ErrStoppedEngine) && h.downloader.Synchronising() {
  698. // should this be warn or debug
  699. p.Log().Debug("Ignoring `stopped engine` consensus error due to active sync.")
  700. continue
  701. }
  702. p.Log().Debug("Ethereum quorum message handling failed", "err", err)
  703. return err
  704. }
  705. }
  706. }
  707. // This is a no-op because the eth handleMsg main loop handle ibf message as well.
  708. func (h *handler) handleConsensus(p *eth.Peer, protoRW p2p.MsgReadWriter, fallThroughBackend eth.Backend) error {
  709. // Read the next message from the remote peer (in protoRW), and ensure it's fully consumed
  710. msg, err := protoRW.ReadMsg()
  711. if err != nil {
  712. return err
  713. }
  714. if msg.Size > protocolMaxMsgSize {
  715. return fmt.Errorf("%w: %v > %v", errMsgTooLarge, msg.Size, protocolMaxMsgSize)
  716. }
  717. defer msg.Discard()
  718. // See if the consensus engine protocol can handle this message, e.g. istanbul will check for message is
  719. // istanbulMsg = 0x11, and NewBlockMsg = 0x07.
  720. handled, err := h.handleConsensusMsg(p, msg)
  721. if handled {
  722. p.Log().Debug("consensus message was handled by consensus engine", "msg", msg.Code,
  723. "quorumConsensusProtocolName", quorumConsensusProtocolName, "err", err)
  724. return err
  725. }
  726. if fallThroughBackend != nil {
  727. var handlers = eth.ETH_65_FULL_SYNC
  728. p.Log().Trace("Message not handled by legacy sub-protocol", "msg", msg.Code)
  729. if handler := handlers[msg.Code]; handler != nil {
  730. p.Log().Debug("Found eth handler for msg", "msg", msg.Code)
  731. return handler(fallThroughBackend, msg, p)
  732. }
  733. }
  734. return nil
  735. }
  736. func (h *handler) handleConsensusMsg(p *eth.Peer, msg p2p.Msg) (bool, error) {
  737. if handler, ok := h.engine.(consensus.Handler); ok {
  738. pubKey := p.Node().Pubkey()
  739. addr := crypto.PubkeyToAddress(*pubKey)
  740. handled, err := handler.HandleMsg(addr, msg)
  741. return handled, err
  742. }
  743. return false, nil
  744. }
  745. // makeLegacyProtocol is basically a copy of the eth makeProtocol, but for legacy subprotocols, e.g. "istanbul/99" "istabnul/64"
  746. // If support legacy subprotocols is removed, remove this and associated code as well.
  747. // If quorum is using a legacy protocol then the "eth" subprotocol should not be available.
  748. func (h *handler) makeLegacyProtocol(protoName string, version uint, length uint64, backend eth.Backend, network uint64, dnsdisc enode.Iterator) p2p.Protocol {
  749. log.Debug("registering a legacy protocol ", "protoName", protoName, "version", version)
  750. return p2p.Protocol{
  751. Name: protoName,
  752. Version: version,
  753. Length: length,
  754. Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
  755. peer := eth.NewPeer(version, p, rw, h.txpool)
  756. return h.runEthPeer(peer, func(peer *eth.Peer) error {
  757. // We pass through the backend so that we can 'handle' messages that we can't handle
  758. return h.handleConsensusLoop(peer, rw, backend)
  759. })
  760. },
  761. NodeInfo: func() interface{} {
  762. return eth.NodeInfoFunc(backend.Chain(), network)
  763. },
  764. PeerInfo: func(id enode.ID) interface{} {
  765. return backend.PeerInfo(id)
  766. },
  767. Attributes: []enr.Entry{eth.CurrentENREntry(backend.Chain())},
  768. DialCandidates: dnsdisc,
  769. }
  770. }
  771. // End Quorum