worker.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  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 miner
  17. import (
  18. "bytes"
  19. "errors"
  20. "math/big"
  21. "sync"
  22. "sync/atomic"
  23. "time"
  24. mapset "github.com/deckarep/golang-set"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/consensus"
  27. "github.com/ethereum/go-ethereum/consensus/misc"
  28. "github.com/ethereum/go-ethereum/core"
  29. "github.com/ethereum/go-ethereum/core/mps"
  30. "github.com/ethereum/go-ethereum/core/rawdb"
  31. "github.com/ethereum/go-ethereum/core/state"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/event"
  34. "github.com/ethereum/go-ethereum/log"
  35. "github.com/ethereum/go-ethereum/params"
  36. "github.com/ethereum/go-ethereum/trie"
  37. )
  38. const (
  39. // resultQueueSize is the size of channel listening to sealing result.
  40. resultQueueSize = 10
  41. // txChanSize is the size of channel listening to NewTxsEvent.
  42. // The number is referenced from the size of tx pool.
  43. txChanSize = 4096
  44. // chainHeadChanSize is the size of channel listening to ChainHeadEvent.
  45. chainHeadChanSize = 10
  46. // chainSideChanSize is the size of channel listening to ChainSideEvent.
  47. chainSideChanSize = 10
  48. // resubmitAdjustChanSize is the size of resubmitting interval adjustment channel.
  49. resubmitAdjustChanSize = 10
  50. // miningLogAtDepth is the number of confirmations before logging successful mining.
  51. miningLogAtDepth = 7
  52. // minRecommitInterval is the minimal time interval to recreate the mining block with
  53. // any newly arrived transactions.
  54. minRecommitInterval = 1 * time.Second
  55. // maxRecommitInterval is the maximum time interval to recreate the mining block with
  56. // any newly arrived transactions.
  57. maxRecommitInterval = 15 * time.Second
  58. // intervalAdjustRatio is the impact a single interval adjustment has on sealing work
  59. // resubmitting interval.
  60. intervalAdjustRatio = 0.1
  61. // intervalAdjustBias is applied during the new resubmit interval calculation in favor of
  62. // increasing upper limit or decreasing lower limit so that the limit can be reachable.
  63. intervalAdjustBias = 200 * 1000.0 * 1000.0
  64. // staleThreshold is the maximum depth of the acceptable stale block.
  65. staleThreshold = 7
  66. )
  67. // environment is the worker's current environment and holds all of the current state information.
  68. type environment struct {
  69. signer types.Signer
  70. state *state.StateDB // apply state changes here
  71. ancestors mapset.Set // ancestor set (used for checking uncle parent validity)
  72. family mapset.Set // family set (used for checking uncle invalidity)
  73. uncles mapset.Set // uncle set
  74. tcount int // tx count in cycle
  75. gasPool *core.GasPool // available gas used to pack transactions
  76. header *types.Header
  77. txs []*types.Transaction
  78. receipts []*types.Receipt
  79. // Quorum
  80. privateReceipts []*types.Receipt
  81. privateStateRepo mps.PrivateStateRepository
  82. // End Quorum
  83. }
  84. // task contains all information for consensus engine sealing and result submitting.
  85. type task struct {
  86. receipts []*types.Receipt
  87. state *state.StateDB
  88. block *types.Block
  89. createdAt time.Time
  90. // Quorum
  91. privateReceipts []*types.Receipt
  92. privateStateRepo mps.PrivateStateRepository
  93. // End Quorum
  94. }
  95. const (
  96. commitInterruptNone int32 = iota
  97. commitInterruptNewHead
  98. commitInterruptResubmit
  99. )
  100. // newWorkReq represents a request for new sealing work submitting with relative interrupt notifier.
  101. type newWorkReq struct {
  102. interrupt *int32
  103. noempty bool
  104. timestamp int64
  105. }
  106. // intervalAdjust represents a resubmitting interval adjustment.
  107. type intervalAdjust struct {
  108. ratio float64
  109. inc bool
  110. }
  111. // worker is the main object which takes care of submitting new work to consensus engine
  112. // and gathering the sealing result.
  113. type worker struct {
  114. config *Config
  115. chainConfig *params.ChainConfig
  116. engine consensus.Engine
  117. eth Backend
  118. chain *core.BlockChain
  119. // Feeds
  120. pendingLogsFeed event.Feed
  121. // Subscriptions
  122. mux *event.TypeMux
  123. txsCh chan core.NewTxsEvent
  124. txsSub event.Subscription
  125. chainHeadCh chan core.ChainHeadEvent
  126. chainHeadSub event.Subscription
  127. chainSideCh chan core.ChainSideEvent
  128. chainSideSub event.Subscription
  129. // Channels
  130. newWorkCh chan *newWorkReq
  131. taskCh chan *task
  132. resultCh chan *types.Block
  133. startCh chan struct{}
  134. exitCh chan struct{}
  135. resubmitIntervalCh chan time.Duration
  136. resubmitAdjustCh chan *intervalAdjust
  137. current *environment // An environment for current running cycle.
  138. localUncles map[common.Hash]*types.Block // A set of side blocks generated locally as the possible uncle blocks.
  139. remoteUncles map[common.Hash]*types.Block // A set of side blocks as the possible uncle blocks.
  140. unconfirmed *unconfirmedBlocks // A set of locally mined blocks pending canonicalness confirmations.
  141. mu sync.RWMutex // The lock used to protect the coinbase and extra fields
  142. coinbase common.Address
  143. extra []byte
  144. pendingMu sync.RWMutex
  145. pendingTasks map[common.Hash]*task
  146. snapshotMu sync.RWMutex // The lock used to protect the block snapshot and state snapshot
  147. snapshotBlock *types.Block
  148. snapshotState *state.StateDB
  149. // atomic status counters
  150. running int32 // The indicator whether the consensus engine is running or not.
  151. newTxs int32 // New arrival transaction count since last sealing work submitting.
  152. // noempty is the flag used to control whether the feature of pre-seal empty
  153. // block is enabled. The default value is false(pre-seal is enabled by default).
  154. // But in some special scenario the consensus engine will seal blocks instantaneously,
  155. // in this case this feature will add all empty blocks into canonical chain
  156. // non-stop and no real transaction will be included.
  157. noempty uint32
  158. // External functions
  159. isLocalBlock func(block *types.Block) bool // Function used to determine whether the specified block is mined by local miner.
  160. // Test hooks
  161. newTaskHook func(*task) // Method to call upon receiving a new sealing task.
  162. skipSealHook func(*task) bool // Method to decide whether skipping the sealing.
  163. fullTaskHook func() // Method to call before pushing the full sealing task.
  164. resubmitHook func(time.Duration, time.Duration) // Method to call upon updating resubmitting interval.
  165. }
  166. func newWorker(config *Config, chainConfig *params.ChainConfig, engine consensus.Engine, eth Backend, mux *event.TypeMux, isLocalBlock func(*types.Block) bool, init bool) *worker {
  167. worker := &worker{
  168. config: config,
  169. chainConfig: chainConfig,
  170. engine: engine,
  171. eth: eth,
  172. mux: mux,
  173. chain: eth.BlockChain(),
  174. isLocalBlock: isLocalBlock,
  175. localUncles: make(map[common.Hash]*types.Block),
  176. remoteUncles: make(map[common.Hash]*types.Block),
  177. unconfirmed: newUnconfirmedBlocks(eth.BlockChain(), miningLogAtDepth),
  178. pendingTasks: make(map[common.Hash]*task),
  179. txsCh: make(chan core.NewTxsEvent, txChanSize),
  180. chainHeadCh: make(chan core.ChainHeadEvent, chainHeadChanSize),
  181. chainSideCh: make(chan core.ChainSideEvent, chainSideChanSize),
  182. newWorkCh: make(chan *newWorkReq),
  183. taskCh: make(chan *task),
  184. resultCh: make(chan *types.Block, resultQueueSize),
  185. exitCh: make(chan struct{}),
  186. startCh: make(chan struct{}, 1),
  187. resubmitIntervalCh: make(chan time.Duration),
  188. resubmitAdjustCh: make(chan *intervalAdjust, resubmitAdjustChanSize),
  189. }
  190. if _, ok := engine.(consensus.Istanbul); ok || !chainConfig.IsQuorum || chainConfig.Clique != nil {
  191. // Subscribe NewTxsEvent for tx pool
  192. worker.txsSub = eth.TxPool().SubscribeNewTxsEvent(worker.txsCh)
  193. // Subscribe events for blockchain
  194. worker.chainHeadSub = eth.BlockChain().SubscribeChainHeadEvent(worker.chainHeadCh)
  195. worker.chainSideSub = eth.BlockChain().SubscribeChainSideEvent(worker.chainSideCh)
  196. // Sanitize recommit interval if the user-specified one is too short.
  197. recommit := worker.config.Recommit
  198. if recommit < minRecommitInterval {
  199. log.Warn("Sanitizing miner recommit interval", "provided", recommit, "updated", minRecommitInterval)
  200. recommit = minRecommitInterval
  201. }
  202. go worker.mainLoop()
  203. go worker.newWorkLoop(recommit)
  204. go worker.resultLoop()
  205. go worker.taskLoop()
  206. // Submit first work to initialize pending state.
  207. if init {
  208. worker.startCh <- struct{}{}
  209. }
  210. }
  211. return worker
  212. }
  213. // setEtherbase sets the etherbase used to initialize the block coinbase field.
  214. func (w *worker) setEtherbase(addr common.Address) {
  215. w.mu.Lock()
  216. defer w.mu.Unlock()
  217. w.coinbase = addr
  218. }
  219. // setExtra sets the content used to initialize the block extra field.
  220. func (w *worker) setExtra(extra []byte) {
  221. w.mu.Lock()
  222. defer w.mu.Unlock()
  223. w.extra = extra
  224. }
  225. // setRecommitInterval updates the interval for miner sealing work recommitting.
  226. func (w *worker) setRecommitInterval(interval time.Duration) {
  227. w.resubmitIntervalCh <- interval
  228. }
  229. // disablePreseal disables pre-sealing mining feature
  230. func (w *worker) disablePreseal() {
  231. atomic.StoreUint32(&w.noempty, 1)
  232. }
  233. // enablePreseal enables pre-sealing mining feature
  234. func (w *worker) enablePreseal() {
  235. atomic.StoreUint32(&w.noempty, 0)
  236. }
  237. // pending returns the pending state and corresponding block.
  238. func (w *worker) pending(psi types.PrivateStateIdentifier) (*types.Block, *state.StateDB, *state.StateDB) {
  239. // return a snapshot to avoid contention on currentMu mutex
  240. w.snapshotMu.RLock()
  241. defer w.snapshotMu.RUnlock()
  242. if w.snapshotState == nil {
  243. return nil, nil, nil
  244. }
  245. privateState, err := w.current.privateStateRepo.StatePSI(psi)
  246. if err != nil {
  247. log.Error("Unable to retrieve private state", "psi", psi, "err", err)
  248. return nil, nil, nil
  249. }
  250. return w.snapshotBlock, w.snapshotState.Copy(), privateState.Copy()
  251. }
  252. // pendingBlock returns pending block.
  253. func (w *worker) pendingBlock() *types.Block {
  254. // return a snapshot to avoid contention on currentMu mutex
  255. w.snapshotMu.RLock()
  256. defer w.snapshotMu.RUnlock()
  257. return w.snapshotBlock
  258. }
  259. // start sets the running status as 1 and triggers new work submitting.
  260. func (w *worker) start() {
  261. atomic.StoreInt32(&w.running, 1)
  262. if istanbul, ok := w.engine.(consensus.Istanbul); ok {
  263. istanbul.Start(w.chain, w.chain.CurrentBlock, rawdb.HasBadBlock)
  264. } else {
  265. log.Warn("no start of engine", "engine", w.engine)
  266. }
  267. w.startCh <- struct{}{}
  268. }
  269. // stop sets the running status as 0.
  270. func (w *worker) stop() {
  271. if istanbul, ok := w.engine.(consensus.Istanbul); ok {
  272. istanbul.Stop()
  273. }
  274. atomic.StoreInt32(&w.running, 0)
  275. }
  276. // isRunning returns an indicator whether worker is running or not.
  277. func (w *worker) isRunning() bool {
  278. return atomic.LoadInt32(&w.running) == 1
  279. }
  280. // close terminates all background threads maintained by the worker.
  281. // Note the worker does not support being closed multiple times.
  282. func (w *worker) close() {
  283. if w.current != nil && w.current.state != nil {
  284. w.current.state.StopPrefetcher()
  285. }
  286. atomic.StoreInt32(&w.running, 0)
  287. close(w.exitCh)
  288. }
  289. // recalcRecommit recalculates the resubmitting interval upon feedback.
  290. func recalcRecommit(minRecommit, prev time.Duration, target float64, inc bool) time.Duration {
  291. var (
  292. prevF = float64(prev.Nanoseconds())
  293. next float64
  294. )
  295. if inc {
  296. next = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target+intervalAdjustBias)
  297. max := float64(maxRecommitInterval.Nanoseconds())
  298. if next > max {
  299. next = max
  300. }
  301. } else {
  302. next = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target-intervalAdjustBias)
  303. min := float64(minRecommit.Nanoseconds())
  304. if next < min {
  305. next = min
  306. }
  307. }
  308. return time.Duration(int64(next))
  309. }
  310. // newWorkLoop is a standalone goroutine to submit new mining work upon received events.
  311. func (w *worker) newWorkLoop(recommit time.Duration) {
  312. var (
  313. interrupt *int32
  314. minRecommit = recommit // minimal resubmit interval specified by user.
  315. timestamp int64 // timestamp for each round of mining.
  316. )
  317. timer := time.NewTimer(0)
  318. defer timer.Stop()
  319. <-timer.C // discard the initial tick
  320. // commit aborts in-flight transaction execution with given signal and resubmits a new one.
  321. commit := func(noempty bool, s int32) {
  322. if interrupt != nil {
  323. atomic.StoreInt32(interrupt, s)
  324. }
  325. interrupt = new(int32)
  326. select {
  327. case w.newWorkCh <- &newWorkReq{interrupt: interrupt, noempty: noempty, timestamp: timestamp}:
  328. case <-w.exitCh:
  329. return
  330. }
  331. timer.Reset(recommit)
  332. atomic.StoreInt32(&w.newTxs, 0)
  333. }
  334. // clearPending cleans the stale pending tasks.
  335. clearPending := func(number uint64) {
  336. w.pendingMu.Lock()
  337. for h, t := range w.pendingTasks {
  338. if t.block.NumberU64()+staleThreshold <= number {
  339. delete(w.pendingTasks, h)
  340. }
  341. }
  342. w.pendingMu.Unlock()
  343. }
  344. for {
  345. select {
  346. case <-w.startCh:
  347. clearPending(w.chain.CurrentBlock().NumberU64())
  348. timestamp = time.Now().Unix()
  349. commit(false, commitInterruptNewHead)
  350. case head := <-w.chainHeadCh:
  351. if h, ok := w.engine.(consensus.Handler); ok {
  352. h.NewChainHead()
  353. }
  354. clearPending(head.Block.NumberU64())
  355. timestamp = time.Now().Unix()
  356. commit(false, commitInterruptNewHead)
  357. case <-timer.C:
  358. // If mining is running resubmit a new work cycle periodically to pull in
  359. // higher priced transactions. Disable this overhead for pending blocks.
  360. if w.isRunning() && (w.chainConfig.Clique == nil || w.chainConfig.Clique.Period > 0) {
  361. // Short circuit if no new transaction arrives.
  362. if atomic.LoadInt32(&w.newTxs) == 0 {
  363. timer.Reset(recommit)
  364. continue
  365. }
  366. commit(true, commitInterruptResubmit)
  367. }
  368. case interval := <-w.resubmitIntervalCh:
  369. // Adjust resubmit interval explicitly by user.
  370. if interval < minRecommitInterval {
  371. log.Warn("Sanitizing miner recommit interval", "provided", interval, "updated", minRecommitInterval)
  372. interval = minRecommitInterval
  373. }
  374. log.Info("Miner recommit interval update", "from", minRecommit, "to", interval)
  375. minRecommit, recommit = interval, interval
  376. if w.resubmitHook != nil {
  377. w.resubmitHook(minRecommit, recommit)
  378. }
  379. case adjust := <-w.resubmitAdjustCh:
  380. // Adjust resubmit interval by feedback.
  381. if adjust.inc {
  382. before := recommit
  383. target := float64(recommit.Nanoseconds()) / adjust.ratio
  384. recommit = recalcRecommit(minRecommit, recommit, target, true)
  385. log.Trace("Increase miner recommit interval", "from", before, "to", recommit)
  386. } else {
  387. before := recommit
  388. recommit = recalcRecommit(minRecommit, recommit, float64(minRecommit.Nanoseconds()), false)
  389. log.Trace("Decrease miner recommit interval", "from", before, "to", recommit)
  390. }
  391. if w.resubmitHook != nil {
  392. w.resubmitHook(minRecommit, recommit)
  393. }
  394. case <-w.exitCh:
  395. return
  396. }
  397. }
  398. }
  399. // mainLoop is a standalone goroutine to regenerate the sealing task based on the received event.
  400. func (w *worker) mainLoop() {
  401. defer w.txsSub.Unsubscribe()
  402. defer w.chainHeadSub.Unsubscribe()
  403. defer w.chainSideSub.Unsubscribe()
  404. for {
  405. select {
  406. case req := <-w.newWorkCh:
  407. w.commitNewWork(req.interrupt, req.noempty, req.timestamp)
  408. case ev := <-w.chainSideCh:
  409. // Short circuit for duplicate side blocks
  410. if _, exist := w.localUncles[ev.Block.Hash()]; exist {
  411. continue
  412. }
  413. if _, exist := w.remoteUncles[ev.Block.Hash()]; exist {
  414. continue
  415. }
  416. // Add side block to possible uncle block set depending on the author.
  417. if w.isLocalBlock != nil && w.isLocalBlock(ev.Block) {
  418. w.localUncles[ev.Block.Hash()] = ev.Block
  419. } else {
  420. w.remoteUncles[ev.Block.Hash()] = ev.Block
  421. }
  422. // If our mining block contains less than 2 uncle blocks,
  423. // add the new uncle block if valid and regenerate a mining block.
  424. if w.isRunning() && w.current != nil && w.current.uncles.Cardinality() < 2 {
  425. start := time.Now()
  426. if err := w.commitUncle(w.current, ev.Block.Header()); err == nil {
  427. var uncles []*types.Header
  428. w.current.uncles.Each(func(item interface{}) bool {
  429. hash, ok := item.(common.Hash)
  430. if !ok {
  431. return false
  432. }
  433. uncle, exist := w.localUncles[hash]
  434. if !exist {
  435. uncle, exist = w.remoteUncles[hash]
  436. }
  437. if !exist {
  438. return false
  439. }
  440. uncles = append(uncles, uncle.Header())
  441. return false
  442. })
  443. w.commit(uncles, nil, true, start)
  444. }
  445. }
  446. case ev := <-w.txsCh:
  447. // Apply transactions to the pending state if we're not mining.
  448. //
  449. // Note all transactions received may not be continuous with transactions
  450. // already included in the current mining block. These transactions will
  451. // be automatically eliminated.
  452. if !w.isRunning() && w.current != nil {
  453. // If block is already full, abort
  454. if gp := w.current.gasPool; gp != nil && gp.Gas() < params.TxGas {
  455. continue
  456. }
  457. w.mu.RLock()
  458. coinbase := w.coinbase
  459. w.mu.RUnlock()
  460. txs := make(map[common.Address]types.Transactions)
  461. for _, tx := range ev.Txs {
  462. acc, _ := types.Sender(w.current.signer, tx)
  463. txs[acc] = append(txs[acc], tx)
  464. }
  465. txset := types.NewTransactionsByPriceAndNonce(w.current.signer, txs)
  466. tcount := w.current.tcount
  467. w.commitTransactions(txset, coinbase, nil)
  468. // Only update the snapshot if any new transactons were added
  469. // to the pending block
  470. if tcount != w.current.tcount {
  471. w.updateSnapshot()
  472. }
  473. } else {
  474. // Special case, if the consensus engine is 0 period clique(dev mode),
  475. // submit mining work here since all empty submission will be rejected
  476. // by clique. Of course the advance sealing(empty submission) is disabled.
  477. if w.chainConfig.Clique != nil && w.chainConfig.Clique.Period == 0 {
  478. w.commitNewWork(nil, true, time.Now().Unix())
  479. }
  480. }
  481. atomic.AddInt32(&w.newTxs, int32(len(ev.Txs)))
  482. // System stopped
  483. case <-w.exitCh:
  484. return
  485. case <-w.txsSub.Err():
  486. return
  487. case <-w.chainHeadSub.Err():
  488. return
  489. case <-w.chainSideSub.Err():
  490. return
  491. }
  492. }
  493. }
  494. // taskLoop is a standalone goroutine to fetch sealing task from the generator and
  495. // push them to consensus engine.
  496. func (w *worker) taskLoop() {
  497. var (
  498. stopCh chan struct{}
  499. prev common.Hash
  500. )
  501. // interrupt aborts the in-flight sealing task.
  502. interrupt := func() {
  503. if stopCh != nil {
  504. close(stopCh)
  505. stopCh = nil
  506. }
  507. }
  508. for {
  509. select {
  510. case task := <-w.taskCh:
  511. if w.newTaskHook != nil {
  512. w.newTaskHook(task)
  513. }
  514. // Reject duplicate sealing work due to resubmitting.
  515. sealHash := w.engine.SealHash(task.block.Header())
  516. if sealHash == prev {
  517. continue
  518. }
  519. // Interrupt previous sealing operation
  520. interrupt()
  521. stopCh, prev = make(chan struct{}), sealHash
  522. if w.skipSealHook != nil && w.skipSealHook(task) {
  523. continue
  524. }
  525. w.pendingMu.Lock()
  526. w.pendingTasks[sealHash] = task
  527. w.pendingMu.Unlock()
  528. if err := w.engine.Seal(w.chain, task.block, w.resultCh, stopCh); err != nil {
  529. log.Warn("Block sealing failed", "err", err)
  530. }
  531. case <-w.exitCh:
  532. interrupt()
  533. return
  534. }
  535. }
  536. }
  537. // resultLoop is a standalone goroutine to handle sealing result submitting
  538. // and flush relative data to the database.
  539. func (w *worker) resultLoop() {
  540. for {
  541. select {
  542. case block := <-w.resultCh:
  543. // Short circuit when receiving empty result.
  544. if block == nil {
  545. continue
  546. }
  547. // Short circuit when receiving duplicate result caused by resubmitting.
  548. if w.chain.HasBlock(block.Hash(), block.NumberU64()) {
  549. continue
  550. }
  551. var (
  552. sealhash = w.engine.SealHash(block.Header())
  553. hash = block.Hash()
  554. )
  555. w.pendingMu.RLock()
  556. task, exist := w.pendingTasks[sealhash]
  557. w.pendingMu.RUnlock()
  558. if !exist {
  559. log.Error("Block found but no relative pending task", "number", block.Number(), "sealhash", sealhash, "hash", hash)
  560. continue
  561. }
  562. // Different block could share same sealhash, deep copy here to prevent write-write conflict.
  563. var (
  564. pubReceipts = make([]*types.Receipt, len(task.receipts))
  565. prvReceipts = make([]*types.Receipt, len(task.privateReceipts))
  566. logs []*types.Log
  567. )
  568. offset := len(task.receipts)
  569. for i, receipt := range task.receipts {
  570. // add block location fields
  571. receipt.BlockHash = hash
  572. receipt.BlockNumber = block.Number()
  573. receipt.TransactionIndex = uint(i)
  574. pubReceipts[i] = new(types.Receipt)
  575. *pubReceipts[i] = *receipt
  576. // Update the block hash in all logs since it is now available and not when the
  577. // receipt/log of individual transactions were created.
  578. for _, log := range receipt.Logs {
  579. log.BlockHash = hash
  580. }
  581. logs = append(logs, receipt.Logs...)
  582. // If this was a public privacy marker transaction then there will be an associated private receipt to handle.
  583. if receipt.PSReceipts != nil {
  584. tx := block.Transaction(receipt.TxHash)
  585. if tx.IsPrivacyMarker() {
  586. for _, markerReceipt := range receipt.PSReceipts {
  587. markerReceipt.BlockHash = hash
  588. markerReceipt.BlockNumber = block.Number()
  589. markerReceipt.TransactionIndex = uint(i)
  590. // Update the block hash in all logs since it is now available and not when the
  591. // receipt/log of individual transactions were created.
  592. for _, log := range markerReceipt.Logs {
  593. log.BlockHash = hash
  594. }
  595. // Note that we don't append logs here, else will get duplicates.
  596. }
  597. }
  598. }
  599. }
  600. for i, receipt := range task.privateReceipts {
  601. // add block location fields
  602. receipt.BlockHash = hash
  603. receipt.BlockNumber = block.Number()
  604. receipt.TransactionIndex = uint(i + offset)
  605. prvReceipts[i] = new(types.Receipt)
  606. *prvReceipts[i] = *receipt
  607. // Update the block hash in all logs since it is now available and not when the
  608. // receipt/log of individual transactions were created.
  609. for _, log := range receipt.Logs {
  610. log.BlockHash = hash
  611. }
  612. logs = append(logs, receipt.Logs...)
  613. for _, psReceipt := range receipt.PSReceipts {
  614. // if block location fields are already populated then this is a privacy marker receipt and it is
  615. // already handled - skip processing it again
  616. if psReceipt.BlockNumber != nil {
  617. continue
  618. }
  619. // add block location fields
  620. psReceipt.BlockHash = hash
  621. psReceipt.BlockNumber = block.Number()
  622. psReceipt.TransactionIndex = uint(i + offset)
  623. // Update the block hash in all logs since it is now available and not when the
  624. // receipt/log of individual transactions were created.
  625. for _, log := range psReceipt.Logs {
  626. log.BlockHash = hash
  627. }
  628. logs = append(logs, psReceipt.Logs...)
  629. }
  630. }
  631. allReceipts := task.privateStateRepo.MergeReceipts(pubReceipts, prvReceipts)
  632. // Commit block and state to database.
  633. _, err := w.chain.WriteBlockWithState(block, allReceipts, logs, task.state, task.privateStateRepo, true)
  634. if err != nil {
  635. log.Error("Failed writing block to chain", "err", err)
  636. continue
  637. }
  638. if err := rawdb.WritePrivateBlockBloom(w.eth.ChainDb(), block.NumberU64(), prvReceipts); err != nil {
  639. log.Error("Failed writing private block bloom", "err", err)
  640. continue
  641. }
  642. log.Info("Successfully sealed new block", "number", block.Number(), "sealhash", sealhash, "hash", hash,
  643. "elapsed", common.PrettyDuration(time.Since(task.createdAt)))
  644. // Broadcast the block and announce chain insertion event
  645. w.mux.Post(core.NewMinedBlockEvent{Block: block})
  646. // Insert the block into the set of pending ones to resultLoop for confirmations
  647. w.unconfirmed.Insert(block.NumberU64(), block.Hash())
  648. case <-w.exitCh:
  649. return
  650. }
  651. }
  652. }
  653. // makeCurrent creates a new environment for the current cycle.
  654. func (w *worker) makeCurrent(parent *types.Block, header *types.Header) error {
  655. // Retrieve the parent state to execute on top and start a prefetcher for
  656. // the miner to speed block sealing up a bit
  657. publicState, privateStateRepo, err := w.chain.StateAt(parent.Root())
  658. if err != nil {
  659. return err
  660. }
  661. publicState.StartPrefetcher("miner")
  662. env := &environment{
  663. signer: types.MakeSigner(w.chainConfig, header.Number),
  664. state: publicState,
  665. ancestors: mapset.NewSet(),
  666. family: mapset.NewSet(),
  667. uncles: mapset.NewSet(),
  668. header: header,
  669. // Quorum
  670. privateStateRepo: privateStateRepo,
  671. }
  672. // when 08 is processed ancestors contain 07 (quick block)
  673. for _, ancestor := range w.chain.GetBlocksFromHash(parent.Hash(), 7) {
  674. for _, uncle := range ancestor.Uncles() {
  675. env.family.Add(uncle.Hash())
  676. }
  677. env.family.Add(ancestor.Hash())
  678. env.ancestors.Add(ancestor.Hash())
  679. }
  680. // Keep track of transactions which return errors so they can be removed
  681. env.tcount = 0
  682. // Swap out the old work with the new one, terminating any leftover prefetcher
  683. // processes in the mean time and starting a new one.
  684. if w.current != nil && w.current.state != nil {
  685. w.current.state.StopPrefetcher()
  686. }
  687. w.current = env
  688. return nil
  689. }
  690. // commitUncle adds the given block to uncle block set, returns error if failed to add.
  691. func (w *worker) commitUncle(env *environment, uncle *types.Header) error {
  692. hash := uncle.Hash()
  693. if env.uncles.Contains(hash) {
  694. return errors.New("uncle not unique")
  695. }
  696. if env.header.ParentHash == uncle.ParentHash {
  697. return errors.New("uncle is sibling")
  698. }
  699. if !env.ancestors.Contains(uncle.ParentHash) {
  700. return errors.New("uncle's parent unknown")
  701. }
  702. if env.family.Contains(hash) {
  703. return errors.New("uncle already included")
  704. }
  705. env.uncles.Add(uncle.Hash())
  706. return nil
  707. }
  708. // updateSnapshot updates pending snapshot block and state.
  709. // Note this function assumes the current variable is thread safe.
  710. func (w *worker) updateSnapshot() {
  711. w.snapshotMu.Lock()
  712. defer w.snapshotMu.Unlock()
  713. var uncles []*types.Header
  714. w.current.uncles.Each(func(item interface{}) bool {
  715. hash, ok := item.(common.Hash)
  716. if !ok {
  717. return false
  718. }
  719. uncle, exist := w.localUncles[hash]
  720. if !exist {
  721. uncle, exist = w.remoteUncles[hash]
  722. }
  723. if !exist {
  724. return false
  725. }
  726. uncles = append(uncles, uncle.Header())
  727. return false
  728. })
  729. w.snapshotBlock = types.NewBlock(
  730. w.current.header,
  731. w.current.txs,
  732. uncles,
  733. w.current.receipts,
  734. trie.NewStackTrie(nil),
  735. )
  736. w.snapshotState = w.current.state.Copy()
  737. }
  738. func (w *worker) commitTransaction(tx *types.Transaction, coinbase common.Address) ([]*types.Log, error) {
  739. workerEnv := w.current
  740. publicStateDB := workerEnv.state
  741. snap := publicStateDB.Snapshot()
  742. privateStateRepo := workerEnv.privateStateRepo
  743. txnStart := time.Now()
  744. mpsReceipt, privateStateSnaphots, err := w.handleMPS(tx, coinbase, false)
  745. if err != nil {
  746. w.revertToPrivateStateSnapshots(privateStateSnaphots)
  747. return nil, err
  748. }
  749. privateStateDB, err := privateStateRepo.DefaultState()
  750. if err != nil {
  751. w.revertToPrivateStateSnapshots(privateStateSnaphots)
  752. return nil, err
  753. }
  754. privateStateDB.Prepare(tx.Hash(), common.Hash{}, workerEnv.tcount)
  755. publicStateDB.Prepare(tx.Hash(), common.Hash{}, workerEnv.tcount)
  756. privateStateSnaphots[privateStateRepo.DefaultStateMetadata().ID] = privateStateDB.Snapshot()
  757. receipt, privateReceipt, err := core.ApplyTransaction(w.chainConfig, w.chain, &coinbase, workerEnv.gasPool, publicStateDB, privateStateDB, workerEnv.header, tx, &workerEnv.header.GasUsed, *w.chain.GetVMConfig(), privateStateRepo.IsMPS(), privateStateRepo, false)
  758. if err != nil {
  759. publicStateDB.RevertToSnapshot(snap)
  760. w.revertToPrivateStateSnapshots(privateStateSnaphots)
  761. return nil, err
  762. }
  763. workerEnv.txs = append(workerEnv.txs, tx)
  764. workerEnv.receipts = append(workerEnv.receipts, receipt)
  765. log.EmitCheckpoint(log.TxCompleted, "tx", tx.Hash().Hex(), "time", time.Since(txnStart))
  766. logs := receipt.Logs
  767. // Quorum
  768. if privateReceipt != nil {
  769. newPrivateReceipt, privateLogs := core.HandlePrivateReceipt(receipt, privateReceipt, mpsReceipt, tx, privateStateDB, privateStateRepo, w.chain)
  770. workerEnv.privateReceipts = append(workerEnv.privateReceipts, newPrivateReceipt)
  771. logs = append(logs, privateLogs...)
  772. }
  773. // End Quorum
  774. return logs, nil
  775. }
  776. func (w *worker) commitTransactions(txs *types.TransactionsByPriceAndNonce, coinbase common.Address, interrupt *int32) bool {
  777. // Short circuit if current is nil
  778. if w.current == nil {
  779. return true
  780. }
  781. if w.current.gasPool == nil {
  782. w.current.gasPool = new(core.GasPool).AddGas(w.current.header.GasLimit)
  783. }
  784. var coalescedLogs []*types.Log
  785. loopStartTime := time.Now() // Quorum
  786. for {
  787. // In the following three cases, we will interrupt the execution of the transaction.
  788. // (1) new head block event arrival, the interrupt signal is 1
  789. // (2) worker start or restart, the interrupt signal is 1
  790. // (3) worker recreate the mining block with any newly arrived transactions, the interrupt signal is 2.
  791. // For the first two cases, the semi-finished work will be discarded.
  792. // For the third case, the semi-finished work will be submitted to the consensus engine.
  793. if interrupt != nil && atomic.LoadInt32(interrupt) != commitInterruptNone {
  794. log.Info("Aborting transaction processing due to 'commitInterruptNewHead',", "elapsed time", time.Since(loopStartTime)) // Quorum
  795. // Notify resubmit loop to increase resubmitting interval due to too frequent commits.
  796. if atomic.LoadInt32(interrupt) == commitInterruptResubmit {
  797. ratio := float64(w.current.header.GasLimit-w.current.gasPool.Gas()) / float64(w.current.header.GasLimit)
  798. if ratio < 0.1 {
  799. ratio = 0.1
  800. }
  801. w.resubmitAdjustCh <- &intervalAdjust{
  802. ratio: ratio,
  803. inc: true,
  804. }
  805. }
  806. return atomic.LoadInt32(interrupt) == commitInterruptNewHead
  807. }
  808. // If we don't have enough gas for any further transactions then we're done
  809. if w.current.gasPool.Gas() < params.TxGas {
  810. log.Trace("Not enough gas for further transactions", "have", w.current.gasPool, "want", params.TxGas)
  811. break
  812. }
  813. // Retrieve the next transaction and abort if all done
  814. tx := txs.Peek()
  815. if tx == nil {
  816. break
  817. }
  818. // Error may be ignored here. The error has already been checked
  819. // during transaction acceptance is the transaction pool.
  820. //
  821. // We use the eip155 signer regardless of the current hf.
  822. from, _ := types.Sender(w.current.signer, tx)
  823. // Check whether the tx is replay protected. If we're not in the EIP155 hf
  824. // phase, start ignoring the sender until we do.
  825. if tx.Protected() && !w.chainConfig.IsEIP155(w.current.header.Number) && !tx.IsPrivate() {
  826. log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", w.chainConfig.EIP155Block)
  827. txs.Pop()
  828. continue
  829. }
  830. // Start executing the transaction
  831. logs, err := w.commitTransaction(tx, coinbase)
  832. switch {
  833. case errors.Is(err, core.ErrGasLimitReached):
  834. // Pop the current out-of-gas transaction without shifting in the next from the account
  835. log.Trace("Gas limit exceeded for current block", "sender", from)
  836. txs.Pop()
  837. case errors.Is(err, core.ErrNonceTooLow):
  838. // New head notification data race between the transaction pool and miner, shift
  839. log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce())
  840. txs.Shift()
  841. case errors.Is(err, core.ErrNonceTooHigh):
  842. // Reorg notification data race between the transaction pool and miner, skip account =
  843. log.Trace("Skipping account with hight nonce", "sender", from, "nonce", tx.Nonce())
  844. txs.Pop()
  845. case errors.Is(err, nil):
  846. // Everything ok, collect the logs and shift in the next transaction from the same account
  847. coalescedLogs = append(coalescedLogs, logs...)
  848. w.current.tcount++
  849. txs.Shift()
  850. case errors.Is(err, core.ErrTxTypeNotSupported):
  851. // Pop the unsupported transaction without shifting in the next from the account
  852. log.Trace("Skipping unsupported transaction type", "sender", from, "type", tx.Type())
  853. txs.Pop()
  854. default:
  855. // Strange error, discard the transaction and get the next in line (note, the
  856. // nonce-too-high clause will prevent us from executing in vain).
  857. log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err)
  858. txs.Shift()
  859. }
  860. }
  861. if !w.isRunning() && len(coalescedLogs) > 0 {
  862. // We don't push the pendingLogsEvent while we are mining. The reason is that
  863. // when we are mining, the worker will regenerate a mining block every 3 seconds.
  864. // In order to avoid pushing the repeated pendingLog, we disable the pending log pushing.
  865. // make a copy, the state caches the logs and these logs get "upgraded" from pending to mined
  866. // logs by filling in the block hash when the block was mined by the local miner. This can
  867. // cause a race condition if a log was "upgraded" before the PendingLogsEvent is processed.
  868. cpy := make([]*types.Log, len(coalescedLogs))
  869. for i, l := range coalescedLogs {
  870. cpy[i] = new(types.Log)
  871. *cpy[i] = *l
  872. }
  873. w.pendingLogsFeed.Send(cpy)
  874. }
  875. // Notify resubmit loop to decrease resubmitting interval if current interval is larger
  876. // than the user-specified one.
  877. if interrupt != nil {
  878. w.resubmitAdjustCh <- &intervalAdjust{inc: false}
  879. }
  880. return false
  881. }
  882. // commitNewWork generates several new sealing tasks based on the parent block.
  883. func (w *worker) commitNewWork(interrupt *int32, noempty bool, timestamp int64) {
  884. w.mu.RLock()
  885. defer w.mu.RUnlock()
  886. tstart := time.Now()
  887. parent := w.chain.CurrentBlock()
  888. if parent.Time() >= uint64(timestamp) {
  889. timestamp = int64(parent.Time() + 1)
  890. }
  891. minGasLimit := w.chainConfig.GetMinerMinGasLimit(parent.Number(), params.DefaultMinGasLimit)
  892. num := parent.Number()
  893. header := &types.Header{
  894. ParentHash: parent.Hash(),
  895. Number: num.Add(num, common.Big1),
  896. GasLimit: core.CalcGasLimit(parent, minGasLimit, w.config.GasFloor, w.config.GasCeil),
  897. Extra: w.extra,
  898. Time: uint64(timestamp),
  899. }
  900. // Only set the coinbase if our consensus engine is running (avoid spurious block rewards)
  901. if w.isRunning() {
  902. if w.coinbase == (common.Address{}) {
  903. log.Error("Refusing to mine without etherbase")
  904. return
  905. }
  906. header.Coinbase = w.coinbase
  907. }
  908. if err := w.engine.Prepare(w.chain, header); err != nil {
  909. log.Error("Failed to prepare header for mining", "err", err)
  910. return
  911. }
  912. // If we are care about TheDAO hard-fork check whether to override the extra-data or not
  913. if daoBlock := w.chainConfig.DAOForkBlock; daoBlock != nil {
  914. // Check whether the block is among the fork extra-override range
  915. limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
  916. if header.Number.Cmp(daoBlock) >= 0 && header.Number.Cmp(limit) < 0 {
  917. // Depending whether we support or oppose the fork, override differently
  918. if w.chainConfig.DAOForkSupport {
  919. header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
  920. } else if bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
  921. header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
  922. }
  923. }
  924. }
  925. // Could potentially happen if starting to mine in an odd state.
  926. err := w.makeCurrent(parent, header)
  927. if err != nil {
  928. log.Error("Failed to create mining context", "err", err)
  929. return
  930. }
  931. // Create the current work task and check any fork transitions needed
  932. env := w.current
  933. if w.chainConfig.DAOForkSupport && w.chainConfig.DAOForkBlock != nil && w.chainConfig.DAOForkBlock.Cmp(header.Number) == 0 {
  934. misc.ApplyDAOHardFork(env.state)
  935. }
  936. // Accumulate the uncles for the current block
  937. uncles := make([]*types.Header, 0, 2)
  938. commitUncles := func(blocks map[common.Hash]*types.Block) {
  939. // Clean up stale uncle blocks first
  940. for hash, uncle := range blocks {
  941. if uncle.NumberU64()+staleThreshold <= header.Number.Uint64() {
  942. delete(blocks, hash)
  943. }
  944. }
  945. for hash, uncle := range blocks {
  946. if len(uncles) == 2 {
  947. break
  948. }
  949. if err := w.commitUncle(env, uncle.Header()); err != nil {
  950. log.Trace("Possible uncle rejected", "hash", hash, "reason", err)
  951. } else {
  952. log.Debug("Committing new uncle to block", "hash", hash)
  953. uncles = append(uncles, uncle.Header())
  954. }
  955. }
  956. }
  957. // Prefer to locally generated uncle
  958. commitUncles(w.localUncles)
  959. commitUncles(w.remoteUncles)
  960. // Create an empty block based on temporary copied state for
  961. // sealing in advance without waiting block execution finished.
  962. if !noempty && atomic.LoadUint32(&w.noempty) == 0 {
  963. w.commit(uncles, nil, false, tstart)
  964. }
  965. // Fill the block with all available pending transactions.
  966. pending, err := w.eth.TxPool().Pending()
  967. if err != nil {
  968. log.Error("Failed to fetch pending transactions", "err", err)
  969. return
  970. }
  971. // Short circuit if there is no available pending transactions.
  972. // But if we disable empty precommit already, ignore it. Since
  973. // empty block is necessary to keep the liveness of the network.
  974. if len(pending) == 0 && atomic.LoadUint32(&w.noempty) == 0 {
  975. w.updateSnapshot()
  976. return
  977. }
  978. // Split the pending transactions into locals and remotes
  979. localTxs, remoteTxs := make(map[common.Address]types.Transactions), pending
  980. for _, account := range w.eth.TxPool().Locals() {
  981. if txs := remoteTxs[account]; len(txs) > 0 {
  982. delete(remoteTxs, account)
  983. localTxs[account] = txs
  984. }
  985. }
  986. if len(localTxs) > 0 {
  987. txs := types.NewTransactionsByPriceAndNonce(w.current.signer, localTxs)
  988. if w.commitTransactions(txs, w.coinbase, interrupt) {
  989. return
  990. }
  991. }
  992. if len(remoteTxs) > 0 {
  993. txs := types.NewTransactionsByPriceAndNonce(w.current.signer, remoteTxs)
  994. if w.commitTransactions(txs, w.coinbase, interrupt) {
  995. return
  996. }
  997. }
  998. w.commit(uncles, w.fullTaskHook, true, tstart)
  999. }
  1000. // commit runs any post-transaction state modifications, assembles the final block
  1001. // and commits new work if consensus engine is running.
  1002. func (w *worker) commit(uncles []*types.Header, interval func(), update bool, start time.Time) error {
  1003. // Deep copy receipts here to avoid interaction between different tasks.
  1004. receipts := copyReceipts(w.current.receipts)
  1005. privateReceipts := copyReceipts(w.current.privateReceipts) // Quorum
  1006. s := w.current.state.Copy()
  1007. psrCopy := w.current.privateStateRepo.Copy()
  1008. block, err := w.engine.FinalizeAndAssemble(w.chain, w.current.header, s, w.current.txs, uncles, receipts)
  1009. if err != nil {
  1010. return err
  1011. }
  1012. if w.isRunning() {
  1013. if interval != nil {
  1014. interval()
  1015. }
  1016. select {
  1017. case w.taskCh <- &task{receipts: receipts, privateReceipts: privateReceipts, state: s, privateStateRepo: psrCopy, block: block, createdAt: time.Now()}:
  1018. w.unconfirmed.Shift(block.NumberU64() - 1)
  1019. log.Info("Commit new mining work", "number", block.Number(), "sealhash", w.engine.SealHash(block.Header()),
  1020. "uncles", len(uncles), "txs", w.current.tcount,
  1021. "gas", block.GasUsed(), "fees", totalFees(block, receipts),
  1022. "elapsed", common.PrettyDuration(time.Since(start)))
  1023. case <-w.exitCh:
  1024. log.Info("Worker has exited")
  1025. }
  1026. }
  1027. if update {
  1028. w.updateSnapshot()
  1029. }
  1030. return nil
  1031. }
  1032. // copyReceipts makes a deep copy of the given receipts.
  1033. func copyReceipts(receipts []*types.Receipt) []*types.Receipt {
  1034. result := make([]*types.Receipt, len(receipts))
  1035. for i, l := range receipts {
  1036. cpy := *l
  1037. result[i] = &cpy
  1038. }
  1039. return result
  1040. }
  1041. // postSideBlock fires a side chain event, only use it for testing.
  1042. func (w *worker) postSideBlock(event core.ChainSideEvent) {
  1043. select {
  1044. case w.chainSideCh <- event:
  1045. case <-w.exitCh:
  1046. }
  1047. }
  1048. // totalFees computes total consumed fees in ETH. Block transactions and receipts have to have the same order.
  1049. func totalFees(block *types.Block, receipts []*types.Receipt) *big.Float {
  1050. feesWei := new(big.Int)
  1051. for i, tx := range block.Transactions() {
  1052. feesWei.Add(feesWei, new(big.Int).Mul(new(big.Int).SetUint64(receipts[i].GasUsed), tx.GasPrice()))
  1053. }
  1054. return new(big.Float).Quo(new(big.Float).SetInt(feesWei), new(big.Float).SetInt(big.NewInt(params.Ether)))
  1055. }
  1056. // Quorum
  1057. //
  1058. // revertToPrivateStateSnapshots attempts to revert all private states to the provided snapshots
  1059. func (w *worker) revertToPrivateStateSnapshots(snapshots map[types.PrivateStateIdentifier]int) {
  1060. for psi, snapshot := range snapshots {
  1061. privateState, err := w.current.privateStateRepo.StatePSI(psi)
  1062. if err == nil {
  1063. privateState.RevertToSnapshot(snapshot)
  1064. } else {
  1065. log.Warn("unable to revert to snapshot", "psi", psi, "snapshot", snapshot, "err", err)
  1066. }
  1067. }
  1068. }
  1069. // Quorum
  1070. //
  1071. // handling MPS scenario for a private transaction. It also captures the snapshot
  1072. // before applying the transaction
  1073. //
  1074. // handleMPS returns the auxiliary receipt and the non-nil snapshots.
  1075. //
  1076. // Caller must check for error and reverts private states.
  1077. func (w *worker) handleMPS(tx *types.Transaction, coinbase common.Address, applyOnPartyOnly bool) (mpsReceipt *types.Receipt, privateStateSnaphots map[types.PrivateStateIdentifier]int, err error) {
  1078. workerEnv := w.current
  1079. privateStateRepo := workerEnv.privateStateRepo
  1080. // make sure we don't return NIL map
  1081. privateStateSnaphots = make(map[types.PrivateStateIdentifier]int)
  1082. if tx.IsPrivate() && privateStateRepo.IsMPS() {
  1083. publicStateDBFactory := func() *state.StateDB {
  1084. db := workerEnv.state.Copy()
  1085. db.Prepare(tx.Hash(), common.Hash{}, workerEnv.tcount)
  1086. return db
  1087. }
  1088. privateStateDBFactory := func(psi types.PrivateStateIdentifier) (*state.StateDB, error) {
  1089. db, err := privateStateRepo.StatePSI(psi)
  1090. if err != nil {
  1091. return nil, err
  1092. }
  1093. db.Prepare(tx.Hash(), common.Hash{}, workerEnv.tcount)
  1094. privateStateSnaphots[psi] = db.Snapshot()
  1095. return db, nil
  1096. }
  1097. mpsReceipt, err = core.ApplyTransactionOnMPS(w.chainConfig, w.chain, &coinbase, workerEnv.gasPool, publicStateDBFactory, privateStateDBFactory, workerEnv.header, tx, &workerEnv.header.GasUsed, *w.chain.GetVMConfig(), privateStateRepo, applyOnPartyOnly, false)
  1098. }
  1099. return
  1100. }