blockchain.go 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768
  1. // Copyright 2014 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 core implements the Ethereum consensus protocol.
  17. package core
  18. import (
  19. "context"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "math/big"
  24. mrand "math/rand"
  25. "sort"
  26. "sync"
  27. "sync/atomic"
  28. "time"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/common/mclock"
  31. "github.com/ethereum/go-ethereum/common/prque"
  32. "github.com/ethereum/go-ethereum/consensus"
  33. "github.com/ethereum/go-ethereum/core/mps"
  34. "github.com/ethereum/go-ethereum/core/privatecache"
  35. "github.com/ethereum/go-ethereum/core/rawdb"
  36. "github.com/ethereum/go-ethereum/core/state"
  37. "github.com/ethereum/go-ethereum/core/state/snapshot"
  38. "github.com/ethereum/go-ethereum/core/types"
  39. "github.com/ethereum/go-ethereum/core/vm"
  40. "github.com/ethereum/go-ethereum/ethdb"
  41. "github.com/ethereum/go-ethereum/event"
  42. "github.com/ethereum/go-ethereum/log"
  43. "github.com/ethereum/go-ethereum/metrics"
  44. "github.com/ethereum/go-ethereum/params"
  45. "github.com/ethereum/go-ethereum/qlight"
  46. "github.com/ethereum/go-ethereum/rlp"
  47. "github.com/ethereum/go-ethereum/trie"
  48. lru "github.com/hashicorp/golang-lru"
  49. )
  50. var (
  51. headBlockGauge = metrics.NewRegisteredGauge("chain/head/block", nil)
  52. headHeaderGauge = metrics.NewRegisteredGauge("chain/head/header", nil)
  53. headFastBlockGauge = metrics.NewRegisteredGauge("chain/head/receipt", nil)
  54. accountReadTimer = metrics.NewRegisteredTimer("chain/account/reads", nil)
  55. accountHashTimer = metrics.NewRegisteredTimer("chain/account/hashes", nil)
  56. accountUpdateTimer = metrics.NewRegisteredTimer("chain/account/updates", nil)
  57. accountCommitTimer = metrics.NewRegisteredTimer("chain/account/commits", nil)
  58. storageReadTimer = metrics.NewRegisteredTimer("chain/storage/reads", nil)
  59. storageHashTimer = metrics.NewRegisteredTimer("chain/storage/hashes", nil)
  60. storageUpdateTimer = metrics.NewRegisteredTimer("chain/storage/updates", nil)
  61. storageCommitTimer = metrics.NewRegisteredTimer("chain/storage/commits", nil)
  62. snapshotAccountReadTimer = metrics.NewRegisteredTimer("chain/snapshot/account/reads", nil)
  63. snapshotStorageReadTimer = metrics.NewRegisteredTimer("chain/snapshot/storage/reads", nil)
  64. snapshotCommitTimer = metrics.NewRegisteredTimer("chain/snapshot/commits", nil)
  65. blockInsertTimer = metrics.NewRegisteredTimer("chain/inserts", nil)
  66. blockValidationTimer = metrics.NewRegisteredTimer("chain/validation", nil)
  67. blockExecutionTimer = metrics.NewRegisteredTimer("chain/execution", nil)
  68. blockWriteTimer = metrics.NewRegisteredTimer("chain/write", nil)
  69. blockReorgMeter = metrics.NewRegisteredMeter("chain/reorg/executes", nil)
  70. blockReorgAddMeter = metrics.NewRegisteredMeter("chain/reorg/add", nil)
  71. blockReorgDropMeter = metrics.NewRegisteredMeter("chain/reorg/drop", nil)
  72. blockReorgInvalidatedTx = metrics.NewRegisteredMeter("chain/reorg/invalidTx", nil)
  73. blockPrefetchExecuteTimer = metrics.NewRegisteredTimer("chain/prefetch/executes", nil)
  74. blockPrefetchInterruptMeter = metrics.NewRegisteredMeter("chain/prefetch/interrupts", nil)
  75. errInsertionInterrupted = errors.New("insertion is interrupted")
  76. )
  77. const (
  78. bodyCacheLimit = 256
  79. blockCacheLimit = 256
  80. receiptsCacheLimit = 32
  81. txLookupCacheLimit = 1024
  82. maxFutureBlocks = 256
  83. maxTimeFutureBlocks = 30
  84. TriesInMemory = 128
  85. // BlockChainVersion ensures that an incompatible database forces a resync from scratch.
  86. //
  87. // Changelog:
  88. //
  89. // - Version 4
  90. // The following incompatible database changes were added:
  91. // * the `BlockNumber`, `TxHash`, `TxIndex`, `BlockHash` and `Index` fields of log are deleted
  92. // * the `Bloom` field of receipt is deleted
  93. // * the `BlockIndex` and `TxIndex` fields of txlookup are deleted
  94. // - Version 5
  95. // The following incompatible database changes were added:
  96. // * the `TxHash`, `GasCost`, and `ContractAddress` fields are no longer stored for a receipt
  97. // * the `TxHash`, `GasCost`, and `ContractAddress` fields are computed by looking up the
  98. // receipts' corresponding block
  99. // - Version 6
  100. // The following incompatible database changes were added:
  101. // * Transaction lookup information stores the corresponding block number instead of block hash
  102. // - Version 7
  103. // The following incompatible database changes were added:
  104. // * Use freezer as the ancient database to maintain all ancient data
  105. // - Version 8
  106. // The following incompatible database changes were added:
  107. // * New scheme for contract code in order to separate the codes and trie nodes
  108. BlockChainVersion uint64 = 8
  109. )
  110. // CacheConfig contains the configuration values for the trie caching/pruning
  111. // that's resident in a blockchain.
  112. type CacheConfig struct {
  113. TrieCleanLimit int // Memory allowance (MB) to use for caching trie nodes in memory
  114. TrieCleanJournal string // Disk journal for saving clean cache entries.
  115. TrieCleanRejournal time.Duration // Time interval to dump clean cache to disk periodically
  116. TrieCleanNoPrefetch bool // Whether to disable heuristic state prefetching for followup blocks
  117. TrieDirtyLimit int // Memory limit (MB) at which to start flushing dirty trie nodes to disk
  118. TrieDirtyDisabled bool // Whether to disable trie write caching and GC altogether (archive node)
  119. TrieTimeLimit time.Duration // Time limit after which to flush the current in-memory trie to disk
  120. SnapshotLimit int // Memory allowance (MB) to use for caching snapshot entries in memory
  121. Preimages bool // Whether to store preimage of trie key to the disk
  122. SnapshotWait bool // Wait for snapshot construction on startup. TODO(karalabe): This is a dirty hack for testing, nuke it
  123. }
  124. // defaultCacheConfig are the default caching values if none are specified by the
  125. // user (also used during testing).
  126. var defaultCacheConfig = &CacheConfig{
  127. TrieCleanLimit: 256,
  128. TrieDirtyLimit: 256,
  129. TrieTimeLimit: 5 * time.Minute,
  130. SnapshotLimit: 256,
  131. SnapshotWait: true,
  132. }
  133. // BlockChain represents the canonical chain given a database with a genesis
  134. // block. The Blockchain manages chain imports, reverts, chain reorganisations.
  135. //
  136. // Importing blocks in to the block chain happens according to the set of rules
  137. // defined by the two stage Validator. Processing of blocks is done using the
  138. // Processor which processes the included transaction. The validation of the state
  139. // is done in the second part of the Validator. Failing results in aborting of
  140. // the import.
  141. //
  142. // The BlockChain also helps in returning blocks from **any** chain included
  143. // in the database as well as blocks that represents the canonical chain. It's
  144. // important to note that GetBlock can return any block and does not need to be
  145. // included in the canonical one where as GetBlockByNumber always represents the
  146. // canonical chain.
  147. type BlockChain struct {
  148. chainConfig *params.ChainConfig // Chain & network configuration
  149. cacheConfig *CacheConfig // Cache configuration for pruning
  150. db ethdb.Database // Low level persistent database to store final content in
  151. snaps *snapshot.Tree // Snapshot tree for fast trie leaf access
  152. triegc *prque.Prque // Priority queue mapping block numbers to tries to gc
  153. gcproc time.Duration // Accumulates canonical block processing for trie dumping
  154. // txLookupLimit is the maximum number of blocks from head whose tx indices
  155. // are reserved:
  156. // * 0: means no limit and regenerate any missing indexes
  157. // * N: means N block limit [HEAD-N+1, HEAD] and delete extra indexes
  158. // * nil: disable tx reindexer/deleter, but still index new blocks
  159. txLookupLimit uint64
  160. hc *HeaderChain
  161. rmLogsFeed event.Feed
  162. chainFeed event.Feed
  163. chainSideFeed event.Feed
  164. chainHeadFeed event.Feed
  165. logsFeed event.Feed
  166. blockProcFeed event.Feed
  167. scope event.SubscriptionScope
  168. genesisBlock *types.Block
  169. chainmu sync.RWMutex // blockchain insertion lock
  170. currentBlock atomic.Value // Current head of the block chain
  171. currentFastBlock atomic.Value // Current head of the fast-sync chain (may be above the block chain!)
  172. stateCache state.Database // State database to reuse between imports (contains state cache)
  173. bodyCache *lru.Cache // Cache for the most recent block bodies
  174. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  175. receiptsCache *lru.Cache // Cache for the most recent receipts per block
  176. blockCache *lru.Cache // Cache for the most recent entire blocks
  177. txLookupCache *lru.Cache // Cache for the most recent transaction lookup data.
  178. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  179. quit chan struct{} // blockchain quit channel
  180. wg sync.WaitGroup // chain processing wait group for shutting down
  181. running int32 // 0 if chain is running, 1 when stopped
  182. procInterrupt int32 // interrupt signaler for block processing
  183. engine consensus.Engine
  184. validator Validator // Block and state validator interface
  185. prefetcher Prefetcher
  186. processor Processor // Block transaction processor interface
  187. vmConfig vm.Config
  188. shouldPreserve func(*types.Block) bool // Function used to determine whether should preserve the given block.
  189. terminateInsert func(common.Hash, uint64) bool // Testing hook used to terminate ancient receipt chain insertion.
  190. // Quorum
  191. quorumConfig *QuorumChainConfig // quorum chain config holds all the possible configuration fields for GoQuorum
  192. setPrivateState func([]*types.Log, *state.StateDB, types.PrivateStateIdentifier) // Function to check extension and set private state
  193. // privateStateManager manages private state(s) for this blockchain
  194. privateStateManager mps.PrivateStateManager
  195. privateStateRootHashValidator qlight.PrivateStateRootHashValidator
  196. // End Quorum
  197. }
  198. // NewBlockChain returns a fully initialised block chain using information
  199. // available in the database. It initialises the default Ethereum Validator and
  200. // Processor.
  201. func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool, txLookupLimit *uint64, quorumChainConfig *QuorumChainConfig) (*BlockChain, error) {
  202. if cacheConfig == nil {
  203. cacheConfig = defaultCacheConfig
  204. }
  205. if quorumChainConfig == nil {
  206. quorumChainConfig = &QuorumChainConfig{}
  207. }
  208. bodyCache, _ := lru.New(bodyCacheLimit)
  209. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  210. receiptsCache, _ := lru.New(receiptsCacheLimit)
  211. blockCache, _ := lru.New(blockCacheLimit)
  212. txLookupCache, _ := lru.New(txLookupCacheLimit)
  213. futureBlocks, _ := lru.New(maxFutureBlocks)
  214. bc := &BlockChain{
  215. chainConfig: chainConfig,
  216. cacheConfig: cacheConfig,
  217. db: db,
  218. triegc: prque.New(nil),
  219. stateCache: state.NewDatabaseWithConfig(db, &trie.Config{
  220. Cache: cacheConfig.TrieCleanLimit,
  221. Journal: cacheConfig.TrieCleanJournal,
  222. Preimages: cacheConfig.Preimages,
  223. }),
  224. quit: make(chan struct{}),
  225. shouldPreserve: shouldPreserve,
  226. bodyCache: bodyCache,
  227. bodyRLPCache: bodyRLPCache,
  228. receiptsCache: receiptsCache,
  229. blockCache: blockCache,
  230. txLookupCache: txLookupCache,
  231. futureBlocks: futureBlocks,
  232. engine: engine,
  233. vmConfig: vmConfig,
  234. // Quorum
  235. quorumConfig: quorumChainConfig,
  236. }
  237. bc.validator = NewBlockValidator(chainConfig, bc, engine)
  238. bc.prefetcher = newStatePrefetcher(chainConfig, bc, engine)
  239. bc.processor = NewStateProcessor(chainConfig, bc, engine)
  240. var err error
  241. privateStateCacheProvider := privatecache.NewPrivateCacheProvider(db, &trie.Config{Cache: cacheConfig.TrieCleanLimit,
  242. Preimages: cacheConfig.Preimages}, bc.stateCache, quorumChainConfig.privateTrieCacheEnabled)
  243. // Quorum: attempt to initialize PSM
  244. if bc.privateStateManager, err = newPrivateStateManager(bc.db, privateStateCacheProvider, chainConfig.IsMPS); err != nil {
  245. return nil, err
  246. }
  247. bc.hc, err = NewHeaderChain(db, chainConfig, engine, bc.insertStopped)
  248. if err != nil {
  249. return nil, err
  250. }
  251. bc.genesisBlock = bc.GetBlockByNumber(0)
  252. if bc.genesisBlock == nil {
  253. return nil, ErrNoGenesis
  254. }
  255. var nilBlock *types.Block
  256. bc.currentBlock.Store(nilBlock)
  257. bc.currentFastBlock.Store(nilBlock)
  258. // Initialize the chain with ancient data if it isn't empty.
  259. var txIndexBlock uint64
  260. if bc.empty() {
  261. rawdb.InitDatabaseFromFreezer(bc.db)
  262. // If ancient database is not empty, reconstruct all missing
  263. // indices in the background.
  264. frozen, _ := bc.db.Ancients()
  265. if frozen > 0 {
  266. txIndexBlock = frozen
  267. }
  268. }
  269. if err := bc.loadLastState(); err != nil {
  270. return nil, err
  271. }
  272. // Make sure the state associated with the block is available
  273. head := bc.CurrentBlock()
  274. if _, err := state.New(head.Root(), bc.stateCache, bc.snaps); err != nil {
  275. // Head state is missing, before the state recovery, find out the
  276. // disk layer point of snapshot(if it's enabled). Make sure the
  277. // rewound point is lower than disk layer.
  278. var diskRoot common.Hash
  279. if bc.cacheConfig.SnapshotLimit > 0 {
  280. diskRoot = rawdb.ReadSnapshotRoot(bc.db)
  281. }
  282. if diskRoot != (common.Hash{}) {
  283. log.Warn("Head state missing, repairing", "number", head.Number(), "hash", head.Hash(), "snaproot", diskRoot)
  284. snapDisk, err := bc.SetHeadBeyondRoot(head.NumberU64(), diskRoot)
  285. if err != nil {
  286. return nil, err
  287. }
  288. // Chain rewound, persist old snapshot number to indicate recovery procedure
  289. if snapDisk != 0 {
  290. rawdb.WriteSnapshotRecoveryNumber(bc.db, snapDisk)
  291. }
  292. } else {
  293. log.Warn("Head state missing, repairing", "number", head.Number(), "hash", head.Hash())
  294. if err := bc.SetHead(head.NumberU64()); err != nil {
  295. return nil, err
  296. }
  297. }
  298. }
  299. // Quorum
  300. if err := bc.privateStateManager.CheckAt(head.Root()); err != nil {
  301. log.Warn("Head private state missing, resetting chain", "number", head.Number(), "hash", head.Hash())
  302. return nil, bc.Reset()
  303. }
  304. // End Quorum
  305. // Ensure that a previous crash in SetHead doesn't leave extra ancients
  306. if frozen, err := bc.db.Ancients(); err == nil && frozen > 0 {
  307. var (
  308. needRewind bool
  309. low uint64
  310. )
  311. // The head full block may be rolled back to a very low height due to
  312. // blockchain repair. If the head full block is even lower than the ancient
  313. // chain, truncate the ancient store.
  314. fullBlock := bc.CurrentBlock()
  315. if fullBlock != nil && fullBlock.Hash() != bc.genesisBlock.Hash() && fullBlock.NumberU64() < frozen-1 {
  316. needRewind = true
  317. low = fullBlock.NumberU64()
  318. }
  319. // In fast sync, it may happen that ancient data has been written to the
  320. // ancient store, but the LastFastBlock has not been updated, truncate the
  321. // extra data here.
  322. fastBlock := bc.CurrentFastBlock()
  323. if fastBlock != nil && fastBlock.NumberU64() < frozen-1 {
  324. needRewind = true
  325. if fastBlock.NumberU64() < low || low == 0 {
  326. low = fastBlock.NumberU64()
  327. }
  328. }
  329. if needRewind {
  330. log.Error("Truncating ancient chain", "from", bc.CurrentHeader().Number.Uint64(), "to", low)
  331. if err := bc.SetHead(low); err != nil {
  332. return nil, err
  333. }
  334. }
  335. }
  336. // The first thing the node will do is reconstruct the verification data for
  337. // the head block (ethash cache or clique voting snapshot). Might as well do
  338. // it in advance.
  339. bc.engine.VerifyHeader(bc, bc.CurrentHeader(), true)
  340. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  341. for hash := range BadHashes {
  342. if header := bc.GetHeaderByHash(hash); header != nil {
  343. // get the canonical block corresponding to the offending header's number
  344. headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
  345. // make sure the headerByNumber (if present) is in our current canonical chain
  346. if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
  347. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  348. if err := bc.SetHead(header.Number.Uint64() - 1); err != nil {
  349. return nil, err
  350. }
  351. log.Error("Chain rewind was successful, resuming normal operation")
  352. }
  353. }
  354. }
  355. // Load any existing snapshot, regenerating it if loading failed
  356. if bc.cacheConfig.SnapshotLimit > 0 {
  357. // If the chain was rewound past the snapshot persistent layer (causing
  358. // a recovery block number to be persisted to disk), check if we're still
  359. // in recovery mode and in that case, don't invalidate the snapshot on a
  360. // head mismatch.
  361. var recover bool
  362. head := bc.CurrentBlock()
  363. if layer := rawdb.ReadSnapshotRecoveryNumber(bc.db); layer != nil && *layer > head.NumberU64() {
  364. log.Warn("Enabling snapshot recovery", "chainhead", head.NumberU64(), "diskbase", *layer)
  365. recover = true
  366. }
  367. bc.snaps, err = snapshot.New(bc.db, bc.stateCache.TrieDB(), bc.cacheConfig.SnapshotLimit, head.Root(), !bc.cacheConfig.SnapshotWait, true, recover)
  368. if err != nil {
  369. log.Error("Error trying to load snapshot", "err", err)
  370. }
  371. }
  372. // Take ownership of this particular state
  373. go bc.update()
  374. if txLookupLimit != nil {
  375. bc.txLookupLimit = *txLookupLimit
  376. bc.wg.Add(1)
  377. go bc.maintainTxIndex(txIndexBlock)
  378. }
  379. // If periodic cache journal is required, spin it up.
  380. if bc.cacheConfig.TrieCleanRejournal > 0 {
  381. if bc.cacheConfig.TrieCleanRejournal < time.Minute {
  382. log.Warn("Sanitizing invalid trie cache journal time", "provided", bc.cacheConfig.TrieCleanRejournal, "updated", time.Minute)
  383. bc.cacheConfig.TrieCleanRejournal = time.Minute
  384. }
  385. triedb := bc.stateCache.TrieDB()
  386. bc.wg.Add(1)
  387. go func() {
  388. defer bc.wg.Done()
  389. triedb.SaveCachePeriodically(bc.cacheConfig.TrieCleanJournal, bc.cacheConfig.TrieCleanRejournal, bc.quit)
  390. }()
  391. }
  392. return bc, nil
  393. }
  394. // Quorum
  395. // Decorates NewBlockChain with multitenancy flag
  396. func NewMultitenantBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool, txLookupLimit *uint64, quorumChainConfig *QuorumChainConfig) (*BlockChain, error) {
  397. if quorumChainConfig == nil {
  398. quorumChainConfig = &QuorumChainConfig{multiTenantEnabled: true}
  399. } else {
  400. quorumChainConfig.multiTenantEnabled = true
  401. }
  402. bc, err := NewBlockChain(db, cacheConfig, chainConfig, engine, vmConfig, shouldPreserve, txLookupLimit, quorumChainConfig)
  403. if err != nil {
  404. return nil, err
  405. }
  406. return bc, err
  407. }
  408. func (bc *BlockChain) PrivateStateManager() mps.PrivateStateManager {
  409. return bc.privateStateManager
  410. }
  411. func (bc *BlockChain) SetPrivateStateManager(psm mps.PrivateStateManager) {
  412. bc.privateStateManager = psm
  413. }
  414. // End Quorum
  415. // GetVMConfig returns the block chain VM config.
  416. func (bc *BlockChain) GetVMConfig() *vm.Config {
  417. return &bc.vmConfig
  418. }
  419. // empty returns an indicator whether the blockchain is empty.
  420. // Note, it's a special case that we connect a non-empty ancient
  421. // database with an empty node, so that we can plugin the ancient
  422. // into node seamlessly.
  423. func (bc *BlockChain) empty() bool {
  424. genesis := bc.genesisBlock.Hash()
  425. for _, hash := range []common.Hash{rawdb.ReadHeadBlockHash(bc.db), rawdb.ReadHeadHeaderHash(bc.db), rawdb.ReadHeadFastBlockHash(bc.db)} {
  426. if hash != genesis {
  427. return false
  428. }
  429. }
  430. return true
  431. }
  432. // loadLastState loads the last known chain state from the database. This method
  433. // assumes that the chain manager mutex is held.
  434. func (bc *BlockChain) loadLastState() error {
  435. // Restore the last known head block
  436. head := rawdb.ReadHeadBlockHash(bc.db)
  437. if head == (common.Hash{}) {
  438. // Corrupt or empty database, init from scratch
  439. log.Warn("Empty database, resetting chain")
  440. return bc.Reset()
  441. }
  442. // Make sure the entire head block is available
  443. currentBlock := bc.GetBlockByHash(head)
  444. if currentBlock == nil {
  445. // Corrupt or empty database, init from scratch
  446. log.Warn("Head block missing, resetting chain", "hash", head)
  447. return bc.Reset()
  448. }
  449. // Quorum
  450. if _, err := bc.privateStateManager.StateRepository(currentBlock.Root()); err != nil {
  451. log.Warn("Head private state missing, resetting chain", "number", currentBlock.Number(), "hash", currentBlock.Hash())
  452. bc.currentBlock.Store(currentBlock)
  453. return bc.Reset()
  454. }
  455. // /Quorum
  456. // Everything seems to be fine, set as the head block
  457. bc.currentBlock.Store(currentBlock)
  458. headBlockGauge.Update(int64(currentBlock.NumberU64()))
  459. // Restore the last known head header
  460. currentHeader := currentBlock.Header()
  461. if head := rawdb.ReadHeadHeaderHash(bc.db); head != (common.Hash{}) {
  462. if header := bc.GetHeaderByHash(head); header != nil {
  463. currentHeader = header
  464. }
  465. }
  466. bc.hc.SetCurrentHeader(currentHeader)
  467. // Restore the last known head fast block
  468. bc.currentFastBlock.Store(currentBlock)
  469. headFastBlockGauge.Update(int64(currentBlock.NumberU64()))
  470. if head := rawdb.ReadHeadFastBlockHash(bc.db); head != (common.Hash{}) {
  471. if block := bc.GetBlockByHash(head); block != nil {
  472. bc.currentFastBlock.Store(block)
  473. headFastBlockGauge.Update(int64(block.NumberU64()))
  474. }
  475. }
  476. // Issue a status log for the user
  477. currentFastBlock := bc.CurrentFastBlock()
  478. headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
  479. blockTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  480. fastTd := bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64())
  481. log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(currentHeader.Time), 0)))
  482. log.Info("Loaded most recent local full block", "number", currentBlock.Number(), "hash", currentBlock.Hash(), "td", blockTd, "age", common.PrettyAge(time.Unix(int64(currentBlock.Time()), 0)))
  483. log.Info("Loaded most recent local fast block", "number", currentFastBlock.Number(), "hash", currentFastBlock.Hash(), "td", fastTd, "age", common.PrettyAge(time.Unix(int64(currentFastBlock.Time()), 0)))
  484. if pivot := rawdb.ReadLastPivotNumber(bc.db); pivot != nil {
  485. log.Info("Loaded last fast-sync pivot marker", "number", *pivot)
  486. }
  487. return nil
  488. }
  489. // SetHead rewinds the local chain to a new head. Depending on whether the node
  490. // was fast synced or full synced and in which state, the method will try to
  491. // delete minimal data from disk whilst retaining chain consistency.
  492. func (bc *BlockChain) SetHead(head uint64) error {
  493. _, err := bc.SetHeadBeyondRoot(head, common.Hash{})
  494. return err
  495. }
  496. // SetHeadBeyondRoot rewinds the local chain to a new head with the extra condition
  497. // that the rewind must pass the specified state root. This method is meant to be
  498. // used when rewinding with snapshots enabled to ensure that we go back further than
  499. // persistent disk layer. Depending on whether the node was fast synced or full, and
  500. // in which state, the method will try to delete minimal data from disk whilst
  501. // retaining chain consistency.
  502. //
  503. // The method returns the block number where the requested root cap was found.
  504. func (bc *BlockChain) SetHeadBeyondRoot(head uint64, root common.Hash) (uint64, error) {
  505. bc.chainmu.Lock()
  506. defer bc.chainmu.Unlock()
  507. // Track the block number of the requested root hash
  508. var rootNumber uint64 // (no root == always 0)
  509. // Retrieve the last pivot block to short circuit rollbacks beyond it and the
  510. // current freezer limit to start nuking id underflown
  511. pivot := rawdb.ReadLastPivotNumber(bc.db)
  512. frozen, _ := bc.db.Ancients()
  513. updateFn := func(db ethdb.KeyValueWriter, header *types.Header) (uint64, bool) {
  514. // Rewind the block chain, ensuring we don't end up with a stateless head
  515. // block. Note, depth equality is permitted to allow using SetHead as a
  516. // chain reparation mechanism without deleting any data!
  517. if currentBlock := bc.CurrentBlock(); currentBlock != nil && header.Number.Uint64() <= currentBlock.NumberU64() {
  518. newHeadBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
  519. if newHeadBlock == nil {
  520. log.Error("Gap in the chain, rewinding to genesis", "number", header.Number, "hash", header.Hash())
  521. newHeadBlock = bc.genesisBlock
  522. } else {
  523. // Block exists, keep rewinding until we find one with state,
  524. // keeping rewinding until we exceed the optional threshold
  525. // root hash
  526. beyondRoot := (root == common.Hash{}) // Flag whether we're beyond the requested root (no root, always true)
  527. for {
  528. // If a root threshold was requested but not yet crossed, check
  529. if root != (common.Hash{}) && !beyondRoot && newHeadBlock.Root() == root {
  530. beyondRoot, rootNumber = true, newHeadBlock.NumberU64()
  531. }
  532. if _, err := state.New(newHeadBlock.Root(), bc.stateCache, bc.snaps); err != nil {
  533. log.Trace("Block state missing, rewinding further", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash())
  534. if pivot == nil || newHeadBlock.NumberU64() > *pivot {
  535. parent := bc.GetBlock(newHeadBlock.ParentHash(), newHeadBlock.NumberU64()-1)
  536. if parent != nil {
  537. newHeadBlock = parent
  538. continue
  539. }
  540. log.Error("Missing block in the middle, aiming genesis", "number", newHeadBlock.NumberU64()-1, "hash", newHeadBlock.ParentHash())
  541. newHeadBlock = bc.genesisBlock
  542. } else {
  543. log.Trace("Rewind passed pivot, aiming genesis", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash(), "pivot", *pivot)
  544. newHeadBlock = bc.genesisBlock
  545. }
  546. }
  547. if beyondRoot || newHeadBlock.NumberU64() == 0 {
  548. log.Debug("Rewound to block with state", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash())
  549. break
  550. }
  551. log.Debug("Skipping block with threshold state", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash(), "root", newHeadBlock.Root())
  552. newHeadBlock = bc.GetBlock(newHeadBlock.ParentHash(), newHeadBlock.NumberU64()-1) // Keep rewinding
  553. }
  554. }
  555. rawdb.WriteHeadBlockHash(db, newHeadBlock.Hash())
  556. // Degrade the chain markers if they are explicitly reverted.
  557. // In theory we should update all in-memory markers in the
  558. // last step, however the direction of SetHead is from high
  559. // to low, so it's safe the update in-memory markers directly.
  560. bc.currentBlock.Store(newHeadBlock)
  561. headBlockGauge.Update(int64(newHeadBlock.NumberU64()))
  562. }
  563. // Rewind the fast block in a simpleton way to the target head
  564. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock != nil && header.Number.Uint64() < currentFastBlock.NumberU64() {
  565. newHeadFastBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
  566. // If either blocks reached nil, reset to the genesis state
  567. if newHeadFastBlock == nil {
  568. newHeadFastBlock = bc.genesisBlock
  569. }
  570. rawdb.WriteHeadFastBlockHash(db, newHeadFastBlock.Hash())
  571. // Degrade the chain markers if they are explicitly reverted.
  572. // In theory we should update all in-memory markers in the
  573. // last step, however the direction of SetHead is from high
  574. // to low, so it's safe the update in-memory markers directly.
  575. bc.currentFastBlock.Store(newHeadFastBlock)
  576. headFastBlockGauge.Update(int64(newHeadFastBlock.NumberU64()))
  577. }
  578. localHead := head
  579. if bc.CurrentBlock() != nil {
  580. localHead = bc.CurrentBlock().NumberU64()
  581. }
  582. // If setHead underflown the freezer threshold and the block processing
  583. // intent afterwards is full block importing, delete the chain segment
  584. // between the stateful-block and the sethead target.
  585. var wipe bool
  586. if localHead+1 < frozen {
  587. wipe = pivot == nil || localHead >= *pivot
  588. }
  589. return localHead, wipe // Only force wipe if full synced
  590. }
  591. // Rewind the header chain, deleting all block bodies until then
  592. delFn := func(db ethdb.KeyValueWriter, hash common.Hash, num uint64) {
  593. // Ignore the error here since light client won't hit this path
  594. frozen, _ := bc.db.Ancients()
  595. if num+1 <= frozen {
  596. // Truncate all relative data(header, total difficulty, body, receipt
  597. // and canonical hash) from ancient store.
  598. if err := bc.db.TruncateAncients(num); err != nil {
  599. log.Crit("Failed to truncate ancient data", "number", num, "err", err)
  600. }
  601. // Remove the hash <-> number mapping from the active store.
  602. rawdb.DeleteHeaderNumber(db, hash)
  603. } else {
  604. // Remove relative body and receipts from the active store.
  605. // The header, total difficulty and canonical hash will be
  606. // removed in the hc.SetHead function.
  607. rawdb.DeleteBody(db, hash, num)
  608. rawdb.DeleteReceipts(db, hash, num)
  609. }
  610. // Todo(rjl493456442) txlookup, bloombits, etc
  611. }
  612. // If SetHead was only called as a chain reparation method, try to skip
  613. // touching the header chain altogether, unless the freezer is broken
  614. if block := bc.CurrentBlock(); block != nil && block.NumberU64() == head {
  615. if target, force := updateFn(bc.db, block.Header()); force {
  616. bc.hc.SetHead(target, updateFn, delFn)
  617. }
  618. } else {
  619. // Rewind the chain to the requested head and keep going backwards until a
  620. // block with a state is found or fast sync pivot is passed
  621. log.Warn("Rewinding blockchain", "target", head)
  622. bc.hc.SetHead(head, updateFn, delFn)
  623. }
  624. // Clear out any stale content from the caches
  625. bc.bodyCache.Purge()
  626. bc.bodyRLPCache.Purge()
  627. bc.receiptsCache.Purge()
  628. bc.blockCache.Purge()
  629. bc.txLookupCache.Purge()
  630. bc.futureBlocks.Purge()
  631. return rootNumber, bc.loadLastState()
  632. }
  633. // FastSyncCommitHead sets the current head block to the one defined by the hash
  634. // irrelevant what the chain contents were prior.
  635. func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
  636. // Make sure that both the block as well at its state trie exists
  637. block := bc.GetBlockByHash(hash)
  638. if block == nil {
  639. return fmt.Errorf("non existent block [%x..]", hash[:4])
  640. }
  641. if _, err := trie.NewSecure(block.Root(), bc.stateCache.TrieDB()); err != nil {
  642. return err
  643. }
  644. // If all checks out, manually set the head block
  645. bc.chainmu.Lock()
  646. bc.currentBlock.Store(block)
  647. headBlockGauge.Update(int64(block.NumberU64()))
  648. bc.chainmu.Unlock()
  649. // Destroy any existing state snapshot and regenerate it in the background,
  650. // also resuming the normal maintenance of any previously paused snapshot.
  651. if bc.snaps != nil {
  652. bc.snaps.Rebuild(block.Root())
  653. }
  654. log.Info("Committed new head block", "number", block.Number(), "hash", hash)
  655. return nil
  656. }
  657. // GasLimit returns the gas limit of the current HEAD block.
  658. func (bc *BlockChain) GasLimit() uint64 {
  659. bc.chainmu.RLock()
  660. defer bc.chainmu.RUnlock()
  661. return bc.CurrentBlock().GasLimit()
  662. }
  663. // CurrentBlock retrieves the current head block of the canonical chain. The
  664. // block is retrieved from the blockchain's internal cache.
  665. func (bc *BlockChain) CurrentBlock() *types.Block {
  666. return bc.currentBlock.Load().(*types.Block)
  667. }
  668. // Snapshots returns the blockchain snapshot tree.
  669. func (bc *BlockChain) Snapshots() *snapshot.Tree {
  670. return bc.snaps
  671. }
  672. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  673. // chain. The block is retrieved from the blockchain's internal cache.
  674. func (bc *BlockChain) CurrentFastBlock() *types.Block {
  675. return bc.currentFastBlock.Load().(*types.Block)
  676. }
  677. // Validator returns the current validator.
  678. func (bc *BlockChain) Validator() Validator {
  679. return bc.validator
  680. }
  681. // Processor returns the current processor.
  682. func (bc *BlockChain) Processor() Processor {
  683. return bc.processor
  684. }
  685. // State returns a new mutable state based on the current HEAD block.
  686. func (bc *BlockChain) State() (*state.StateDB, mps.PrivateStateRepository, error) {
  687. return bc.StateAt(bc.CurrentBlock().Root())
  688. }
  689. // Quorum
  690. //
  691. // StatePSI returns a new mutable public state and a mutable private state for given PSI,
  692. // based on the current HEAD block.
  693. func (bc *BlockChain) StatePSI(psi types.PrivateStateIdentifier) (*state.StateDB, *state.StateDB, error) {
  694. return bc.StateAtPSI(bc.CurrentBlock().Root(), psi)
  695. }
  696. // Quorum
  697. //
  698. // SetPrivateStateRootHashValidator allows injecting a private state root hash validator
  699. func (bc *BlockChain) SetPrivateStateRootHashValidator(psrhv qlight.PrivateStateRootHashValidator) {
  700. bc.privateStateRootHashValidator = psrhv
  701. }
  702. // StatePSI returns a new mutable public state and a mutable private state for the given PSI,
  703. // based on a particular point in time.
  704. func (bc *BlockChain) StateAtPSI(root common.Hash, psi types.PrivateStateIdentifier) (*state.StateDB, *state.StateDB, error) {
  705. publicStateDb, privateStateRepo, err := bc.StateAt(root)
  706. if err != nil {
  707. return nil, nil, err
  708. }
  709. privateStateDb, privateStateDbErr := privateStateRepo.StatePSI(psi)
  710. if privateStateDbErr != nil {
  711. return nil, nil, privateStateDbErr
  712. }
  713. return publicStateDb, privateStateDb, nil
  714. }
  715. // StateAt returns a new mutable public state and a new mutable private state repo
  716. // based on a particular point in time. The returned private state repo can be used
  717. // to obtain a mutable private state for a given PSI
  718. func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, mps.PrivateStateRepository, error) {
  719. publicStateDb, publicStateDbErr := state.New(root, bc.stateCache, bc.snaps)
  720. if publicStateDbErr != nil {
  721. return nil, nil, publicStateDbErr
  722. }
  723. privateStateRepo, privateStateRepoErr := bc.privateStateManager.StateRepository(root)
  724. if privateStateRepoErr != nil {
  725. return nil, nil, privateStateRepoErr
  726. }
  727. return publicStateDb, privateStateRepo, nil
  728. }
  729. // StateCache returns the caching database underpinning the blockchain instance.
  730. func (bc *BlockChain) StateCache() state.Database {
  731. return bc.stateCache
  732. }
  733. // Reset purges the entire blockchain, restoring it to its genesis state.
  734. func (bc *BlockChain) Reset() error {
  735. return bc.ResetWithGenesisBlock(bc.genesisBlock)
  736. }
  737. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  738. // specified genesis state.
  739. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
  740. // Dump the entire block chain and purge the caches
  741. if err := bc.SetHead(0); err != nil {
  742. return err
  743. }
  744. bc.chainmu.Lock()
  745. defer bc.chainmu.Unlock()
  746. // Prepare the genesis block and reinitialise the chain
  747. batch := bc.db.NewBatch()
  748. rawdb.WriteTd(batch, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty())
  749. rawdb.WriteBlock(batch, genesis)
  750. if err := batch.Write(); err != nil {
  751. log.Crit("Failed to write genesis block", "err", err)
  752. }
  753. bc.writeHeadBlock(genesis)
  754. // Last update all in-memory chain markers
  755. bc.genesisBlock = genesis
  756. bc.currentBlock.Store(bc.genesisBlock)
  757. headBlockGauge.Update(int64(bc.genesisBlock.NumberU64()))
  758. bc.hc.SetGenesis(bc.genesisBlock.Header())
  759. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  760. bc.currentFastBlock.Store(bc.genesisBlock)
  761. headFastBlockGauge.Update(int64(bc.genesisBlock.NumberU64()))
  762. return nil
  763. }
  764. // Export writes the active chain to the given writer.
  765. func (bc *BlockChain) Export(w io.Writer) error {
  766. return bc.ExportN(w, uint64(0), bc.CurrentBlock().NumberU64())
  767. }
  768. // ExportN writes a subset of the active chain to the given writer.
  769. func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  770. bc.chainmu.RLock()
  771. defer bc.chainmu.RUnlock()
  772. if first > last {
  773. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  774. }
  775. log.Info("Exporting batch of blocks", "count", last-first+1)
  776. start, reported := time.Now(), time.Now()
  777. for nr := first; nr <= last; nr++ {
  778. block := bc.GetBlockByNumber(nr)
  779. if block == nil {
  780. return fmt.Errorf("export failed on #%d: not found", nr)
  781. }
  782. if err := block.EncodeRLP(w); err != nil {
  783. return err
  784. }
  785. if time.Since(reported) >= statsReportLimit {
  786. log.Info("Exporting blocks", "exported", block.NumberU64()-first, "elapsed", common.PrettyDuration(time.Since(start)))
  787. reported = time.Now()
  788. }
  789. }
  790. return nil
  791. }
  792. // writeHeadBlock injects a new head block into the current block chain. This method
  793. // assumes that the block is indeed a true head. It will also reset the head
  794. // header and the head fast sync block to this very same block if they are older
  795. // or if they are on a different side chain.
  796. //
  797. // Note, this function assumes that the `mu` mutex is held!
  798. func (bc *BlockChain) writeHeadBlock(block *types.Block) {
  799. // If the block is on a side chain or an unknown one, force other heads onto it too
  800. updateHeads := rawdb.ReadCanonicalHash(bc.db, block.NumberU64()) != block.Hash()
  801. // Add the block to the canonical chain number scheme and mark as the head
  802. batch := bc.db.NewBatch()
  803. rawdb.WriteCanonicalHash(batch, block.Hash(), block.NumberU64())
  804. rawdb.WriteTxLookupEntriesByBlock(batch, block)
  805. rawdb.WriteHeadBlockHash(batch, block.Hash())
  806. // If the block is better than our head or is on a different chain, force update heads
  807. if updateHeads {
  808. rawdb.WriteHeadHeaderHash(batch, block.Hash())
  809. rawdb.WriteHeadFastBlockHash(batch, block.Hash())
  810. }
  811. // Flush the whole batch into the disk, exit the node if failed
  812. if err := batch.Write(); err != nil {
  813. log.Crit("Failed to update chain indexes and markers", "err", err)
  814. }
  815. // Update all in-memory chain markers in the last step
  816. if updateHeads {
  817. bc.hc.SetCurrentHeader(block.Header())
  818. bc.currentFastBlock.Store(block)
  819. headFastBlockGauge.Update(int64(block.NumberU64()))
  820. }
  821. bc.currentBlock.Store(block)
  822. headBlockGauge.Update(int64(block.NumberU64()))
  823. }
  824. // Genesis retrieves the chain's genesis block.
  825. func (bc *BlockChain) Genesis() *types.Block {
  826. return bc.genesisBlock
  827. }
  828. // GetBody retrieves a block body (transactions and uncles) from the database by
  829. // hash, caching it if found.
  830. func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {
  831. // Short circuit if the body's already in the cache, retrieve otherwise
  832. if cached, ok := bc.bodyCache.Get(hash); ok {
  833. body := cached.(*types.Body)
  834. return body
  835. }
  836. number := bc.hc.GetBlockNumber(hash)
  837. if number == nil {
  838. return nil
  839. }
  840. body := rawdb.ReadBody(bc.db, hash, *number)
  841. if body == nil {
  842. return nil
  843. }
  844. // Cache the found body for next time and return
  845. bc.bodyCache.Add(hash, body)
  846. return body
  847. }
  848. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  849. // caching it if found.
  850. func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  851. // Short circuit if the body's already in the cache, retrieve otherwise
  852. if cached, ok := bc.bodyRLPCache.Get(hash); ok {
  853. return cached.(rlp.RawValue)
  854. }
  855. number := bc.hc.GetBlockNumber(hash)
  856. if number == nil {
  857. return nil
  858. }
  859. body := rawdb.ReadBodyRLP(bc.db, hash, *number)
  860. if len(body) == 0 {
  861. return nil
  862. }
  863. // Cache the found body for next time and return
  864. bc.bodyRLPCache.Add(hash, body)
  865. return body
  866. }
  867. // HasBlock checks if a block is fully present in the database or not.
  868. func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
  869. if bc.blockCache.Contains(hash) {
  870. return true
  871. }
  872. return rawdb.HasBody(bc.db, hash, number)
  873. }
  874. // HasFastBlock checks if a fast block is fully present in the database or not.
  875. func (bc *BlockChain) HasFastBlock(hash common.Hash, number uint64) bool {
  876. if !bc.HasBlock(hash, number) {
  877. return false
  878. }
  879. if bc.receiptsCache.Contains(hash) {
  880. return true
  881. }
  882. return rawdb.HasReceipts(bc.db, hash, number)
  883. }
  884. // HasState checks if state trie is fully present in the database or not.
  885. func (bc *BlockChain) HasState(hash common.Hash) bool {
  886. _, err := bc.stateCache.OpenTrie(hash)
  887. return err == nil
  888. }
  889. // HasBlockAndState checks if a block and associated state trie is fully present
  890. // in the database or not, caching it if present.
  891. func (bc *BlockChain) HasBlockAndState(hash common.Hash, number uint64) bool {
  892. // Check first that the block itself is known
  893. block := bc.GetBlock(hash, number)
  894. if block == nil {
  895. return false
  896. }
  897. return bc.HasState(block.Root())
  898. }
  899. // GetBlock retrieves a block from the database by hash and number,
  900. // caching it if found.
  901. func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  902. // Short circuit if the block's already in the cache, retrieve otherwise
  903. if block, ok := bc.blockCache.Get(hash); ok {
  904. return block.(*types.Block)
  905. }
  906. block := rawdb.ReadBlock(bc.db, hash, number)
  907. if block == nil {
  908. return nil
  909. }
  910. // Cache the found block for next time and return
  911. bc.blockCache.Add(block.Hash(), block)
  912. return block
  913. }
  914. // GetBlockByHash retrieves a block from the database by hash, caching it if found.
  915. func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
  916. number := bc.hc.GetBlockNumber(hash)
  917. if number == nil {
  918. return nil
  919. }
  920. return bc.GetBlock(hash, *number)
  921. }
  922. // GetBlockByNumber retrieves a block from the database by number, caching it
  923. // (associated with its hash) if found.
  924. func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  925. hash := rawdb.ReadCanonicalHash(bc.db, number)
  926. if hash == (common.Hash{}) {
  927. return nil
  928. }
  929. return bc.GetBlock(hash, number)
  930. }
  931. // GetReceiptsByHash retrieves the receipts for all transactions in a given block.
  932. func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) types.Receipts {
  933. if receipts, ok := bc.receiptsCache.Get(hash); ok {
  934. return receipts.(types.Receipts)
  935. }
  936. number := rawdb.ReadHeaderNumber(bc.db, hash)
  937. if number == nil {
  938. return nil
  939. }
  940. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  941. if receipts == nil {
  942. return nil
  943. }
  944. bc.receiptsCache.Add(hash, receipts)
  945. return receipts
  946. }
  947. // (Quorum) GetPMTPrivateReceiptsByHash retrieves the receipts for all internal private transactions (i.e. the private
  948. // transaction for a privacy marker transaction) in a given block.
  949. func (bc *BlockChain) GetPMTPrivateReceiptsByHash(ctx context.Context, hash common.Hash) (types.Receipts, error) {
  950. psm, err := bc.privateStateManager.ResolveForUserContext(ctx)
  951. if err != nil {
  952. return nil, err
  953. }
  954. allReceipts := bc.GetReceiptsByHash(hash)
  955. block := bc.GetBlockByHash(hash)
  956. if block == nil {
  957. return types.Receipts{}, nil
  958. }
  959. privateReceipts := make([]*types.Receipt, 0)
  960. for i, tx := range block.Transactions() {
  961. if tx.IsPrivacyMarker() {
  962. receipt := allReceipts[i]
  963. if receipt.PSReceipts != nil && receipt.PSReceipts[psm.ID] != nil {
  964. privateReceipts = append(privateReceipts, receipt.PSReceipts[psm.ID])
  965. } else {
  966. return nil, errors.New("could not find receipt for private transaction")
  967. }
  968. }
  969. }
  970. return privateReceipts, nil
  971. }
  972. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  973. // [deprecated by eth/62]
  974. func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  975. number := bc.hc.GetBlockNumber(hash)
  976. if number == nil {
  977. return nil
  978. }
  979. for i := 0; i < n; i++ {
  980. block := bc.GetBlock(hash, *number)
  981. if block == nil {
  982. break
  983. }
  984. blocks = append(blocks, block)
  985. hash = block.ParentHash()
  986. *number--
  987. }
  988. return
  989. }
  990. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  991. // a specific distance is reached.
  992. func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  993. uncles := []*types.Header{}
  994. for i := 0; block != nil && i < length; i++ {
  995. uncles = append(uncles, block.Uncles()...)
  996. block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  997. }
  998. return uncles
  999. }
  1000. // TrieNode retrieves a blob of data associated with a trie node
  1001. // either from ephemeral in-memory cache, or from persistent storage.
  1002. func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error) {
  1003. return bc.stateCache.TrieDB().Node(hash)
  1004. }
  1005. // ContractCode retrieves a blob of data associated with a contract hash
  1006. // either from ephemeral in-memory cache, or from persistent storage.
  1007. func (bc *BlockChain) ContractCode(hash common.Hash) ([]byte, error) {
  1008. return bc.stateCache.ContractCode(common.Hash{}, hash)
  1009. }
  1010. // ContractCodeWithPrefix retrieves a blob of data associated with a contract
  1011. // hash either from ephemeral in-memory cache, or from persistent storage.
  1012. //
  1013. // If the code doesn't exist in the in-memory cache, check the storage with
  1014. // new code scheme.
  1015. func (bc *BlockChain) ContractCodeWithPrefix(hash common.Hash) ([]byte, error) {
  1016. type codeReader interface {
  1017. ContractCodeWithPrefix(addrHash, codeHash common.Hash) ([]byte, error)
  1018. }
  1019. return bc.stateCache.(codeReader).ContractCodeWithPrefix(common.Hash{}, hash)
  1020. }
  1021. // Stop stops the blockchain service. If any imports are currently in progress
  1022. // it will abort them using the procInterrupt.
  1023. func (bc *BlockChain) Stop() {
  1024. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  1025. return
  1026. }
  1027. // Unsubscribe all subscriptions registered from blockchain
  1028. bc.scope.Close()
  1029. close(bc.quit)
  1030. bc.StopInsert()
  1031. bc.wg.Wait()
  1032. // Ensure that the entirety of the state snapshot is journalled to disk.
  1033. var snapBase common.Hash
  1034. if bc.snaps != nil {
  1035. var err error
  1036. if snapBase, err = bc.snaps.Journal(bc.CurrentBlock().Root()); err != nil {
  1037. log.Error("Failed to journal state snapshot", "err", err)
  1038. }
  1039. }
  1040. // Ensure the state of a recent block is also stored to disk before exiting.
  1041. // We're writing three different states to catch different restart scenarios:
  1042. // - HEAD: So we don't need to reprocess any blocks in the general case
  1043. // - HEAD-1: So we don't do large reorgs if our HEAD becomes an uncle
  1044. // - HEAD-127: So we have a hard limit on the number of blocks reexecuted
  1045. if !bc.cacheConfig.TrieDirtyDisabled {
  1046. triedb := bc.stateCache.TrieDB()
  1047. for _, offset := range []uint64{0, 1, TriesInMemory - 1} {
  1048. if number := bc.CurrentBlock().NumberU64(); number > offset {
  1049. recent := bc.GetBlockByNumber(number - offset)
  1050. log.Info("Writing cached state to disk", "block", recent.Number(), "hash", recent.Hash(), "root", recent.Root())
  1051. if err := triedb.Commit(recent.Root(), true, nil); err != nil {
  1052. log.Error("Failed to commit recent state trie", "err", err)
  1053. }
  1054. }
  1055. }
  1056. if snapBase != (common.Hash{}) {
  1057. log.Info("Writing snapshot state to disk", "root", snapBase)
  1058. if err := triedb.Commit(snapBase, true, nil); err != nil {
  1059. log.Error("Failed to commit recent state trie", "err", err)
  1060. }
  1061. }
  1062. for !bc.triegc.Empty() {
  1063. triedb.Dereference(bc.triegc.PopItem().(common.Hash))
  1064. }
  1065. if size, _ := triedb.Size(); size != 0 {
  1066. log.Error("Dangling trie nodes after full cleanup")
  1067. }
  1068. }
  1069. // Ensure all live cached entries be saved into disk, so that we can skip
  1070. // cache warmup when node restarts.
  1071. if bc.cacheConfig.TrieCleanJournal != "" {
  1072. triedb := bc.stateCache.TrieDB()
  1073. triedb.SaveCache(bc.cacheConfig.TrieCleanJournal)
  1074. }
  1075. log.Info("Blockchain stopped")
  1076. }
  1077. // StopInsert interrupts all insertion methods, causing them to return
  1078. // errInsertionInterrupted as soon as possible. Insertion is permanently disabled after
  1079. // calling this method.
  1080. func (bc *BlockChain) StopInsert() {
  1081. atomic.StoreInt32(&bc.procInterrupt, 1)
  1082. }
  1083. // insertStopped returns true after StopInsert has been called.
  1084. func (bc *BlockChain) insertStopped() bool {
  1085. return atomic.LoadInt32(&bc.procInterrupt) == 1
  1086. }
  1087. func (bc *BlockChain) procFutureBlocks() {
  1088. blocks := make([]*types.Block, 0, bc.futureBlocks.Len())
  1089. for _, hash := range bc.futureBlocks.Keys() {
  1090. if block, exist := bc.futureBlocks.Peek(hash); exist {
  1091. blocks = append(blocks, block.(*types.Block))
  1092. }
  1093. }
  1094. if len(blocks) > 0 {
  1095. sort.Slice(blocks, func(i, j int) bool {
  1096. return blocks[i].NumberU64() < blocks[j].NumberU64()
  1097. })
  1098. // Insert one by one as chain insertion needs contiguous ancestry between blocks
  1099. for i := range blocks {
  1100. bc.InsertChain(blocks[i : i+1])
  1101. }
  1102. }
  1103. }
  1104. // WriteStatus status of write
  1105. type WriteStatus byte
  1106. const (
  1107. NonStatTy WriteStatus = iota
  1108. CanonStatTy
  1109. SideStatTy
  1110. )
  1111. // truncateAncient rewinds the blockchain to the specified header and deletes all
  1112. // data in the ancient store that exceeds the specified header.
  1113. func (bc *BlockChain) truncateAncient(head uint64) error {
  1114. frozen, err := bc.db.Ancients()
  1115. if err != nil {
  1116. return err
  1117. }
  1118. // Short circuit if there is no data to truncate in ancient store.
  1119. if frozen <= head+1 {
  1120. return nil
  1121. }
  1122. // Truncate all the data in the freezer beyond the specified head
  1123. if err := bc.db.TruncateAncients(head + 1); err != nil {
  1124. return err
  1125. }
  1126. // Clear out any stale content from the caches
  1127. bc.hc.headerCache.Purge()
  1128. bc.hc.tdCache.Purge()
  1129. bc.hc.numberCache.Purge()
  1130. // Clear out any stale content from the caches
  1131. bc.bodyCache.Purge()
  1132. bc.bodyRLPCache.Purge()
  1133. bc.receiptsCache.Purge()
  1134. bc.blockCache.Purge()
  1135. bc.txLookupCache.Purge()
  1136. bc.futureBlocks.Purge()
  1137. log.Info("Rewind ancient data", "number", head)
  1138. return nil
  1139. }
  1140. // numberHash is just a container for a number and a hash, to represent a block
  1141. type numberHash struct {
  1142. number uint64
  1143. hash common.Hash
  1144. }
  1145. // InsertReceiptChain attempts to complete an already existing header chain with
  1146. // transaction and receipt data.
  1147. func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts, ancientLimit uint64) (int, error) {
  1148. // We don't require the chainMu here since we want to maximize the
  1149. // concurrency of header insertion and receipt insertion.
  1150. bc.wg.Add(1)
  1151. defer bc.wg.Done()
  1152. var (
  1153. ancientBlocks, liveBlocks types.Blocks
  1154. ancientReceipts, liveReceipts []types.Receipts
  1155. )
  1156. // Do a sanity check that the provided chain is actually ordered and linked
  1157. for i := 0; i < len(blockChain); i++ {
  1158. if i != 0 {
  1159. if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
  1160. log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
  1161. "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
  1162. return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x..], item %d is #%d [%x..] (parent [%x..])", i-1, blockChain[i-1].NumberU64(),
  1163. blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
  1164. }
  1165. }
  1166. if blockChain[i].NumberU64() <= ancientLimit {
  1167. ancientBlocks, ancientReceipts = append(ancientBlocks, blockChain[i]), append(ancientReceipts, receiptChain[i])
  1168. } else {
  1169. liveBlocks, liveReceipts = append(liveBlocks, blockChain[i]), append(liveReceipts, receiptChain[i])
  1170. }
  1171. }
  1172. var (
  1173. stats = struct{ processed, ignored int32 }{}
  1174. start = time.Now()
  1175. size = 0
  1176. )
  1177. // updateHead updates the head fast sync block if the inserted blocks are better
  1178. // and returns an indicator whether the inserted blocks are canonical.
  1179. updateHead := func(head *types.Block) bool {
  1180. bc.chainmu.Lock()
  1181. // Rewind may have occurred, skip in that case.
  1182. if bc.CurrentHeader().Number.Cmp(head.Number()) >= 0 {
  1183. currentFastBlock, td := bc.CurrentFastBlock(), bc.GetTd(head.Hash(), head.NumberU64())
  1184. if bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()).Cmp(td) < 0 {
  1185. rawdb.WriteHeadFastBlockHash(bc.db, head.Hash())
  1186. bc.currentFastBlock.Store(head)
  1187. headFastBlockGauge.Update(int64(head.NumberU64()))
  1188. bc.chainmu.Unlock()
  1189. return true
  1190. }
  1191. }
  1192. bc.chainmu.Unlock()
  1193. return false
  1194. }
  1195. // writeAncient writes blockchain and corresponding receipt chain into ancient store.
  1196. //
  1197. // this function only accepts canonical chain data. All side chain will be reverted
  1198. // eventually.
  1199. writeAncient := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  1200. var (
  1201. previous = bc.CurrentFastBlock()
  1202. batch = bc.db.NewBatch()
  1203. )
  1204. // If any error occurs before updating the head or we are inserting a side chain,
  1205. // all the data written this time wll be rolled back.
  1206. defer func() {
  1207. if previous != nil {
  1208. if err := bc.truncateAncient(previous.NumberU64()); err != nil {
  1209. log.Crit("Truncate ancient store failed", "err", err)
  1210. }
  1211. }
  1212. }()
  1213. var deleted []*numberHash
  1214. for i, block := range blockChain {
  1215. // Short circuit insertion if shutting down or processing failed
  1216. if bc.insertStopped() {
  1217. return 0, errInsertionInterrupted
  1218. }
  1219. // Short circuit insertion if it is required(used in testing only)
  1220. if bc.terminateInsert != nil && bc.terminateInsert(block.Hash(), block.NumberU64()) {
  1221. return i, errors.New("insertion is terminated for testing purpose")
  1222. }
  1223. // Short circuit if the owner header is unknown
  1224. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  1225. return i, fmt.Errorf("containing header #%d [%x..] unknown", block.Number(), block.Hash().Bytes()[:4])
  1226. }
  1227. if block.NumberU64() == 1 {
  1228. // Make sure to write the genesis into the freezer
  1229. if frozen, _ := bc.db.Ancients(); frozen == 0 {
  1230. h := rawdb.ReadCanonicalHash(bc.db, 0)
  1231. b := rawdb.ReadBlock(bc.db, h, 0)
  1232. size += rawdb.WriteAncientBlock(bc.db, b, rawdb.ReadReceipts(bc.db, h, 0, bc.chainConfig), rawdb.ReadTd(bc.db, h, 0))
  1233. log.Info("Wrote genesis to ancients")
  1234. }
  1235. }
  1236. // Flush data into ancient database.
  1237. size += rawdb.WriteAncientBlock(bc.db, block, receiptChain[i], bc.GetTd(block.Hash(), block.NumberU64()))
  1238. // Write tx indices if any condition is satisfied:
  1239. // * If user requires to reserve all tx indices(txlookuplimit=0)
  1240. // * If all ancient tx indices are required to be reserved(txlookuplimit is even higher than ancientlimit)
  1241. // * If block number is large enough to be regarded as a recent block
  1242. // It means blocks below the ancientLimit-txlookupLimit won't be indexed.
  1243. //
  1244. // But if the `TxIndexTail` is not nil, e.g. Geth is initialized with
  1245. // an external ancient database, during the setup, blockchain will start
  1246. // a background routine to re-indexed all indices in [ancients - txlookupLimit, ancients)
  1247. // range. In this case, all tx indices of newly imported blocks should be
  1248. // generated.
  1249. if bc.txLookupLimit == 0 || ancientLimit <= bc.txLookupLimit || block.NumberU64() >= ancientLimit-bc.txLookupLimit {
  1250. rawdb.WriteTxLookupEntriesByBlock(batch, block)
  1251. } else if rawdb.ReadTxIndexTail(bc.db) != nil {
  1252. rawdb.WriteTxLookupEntriesByBlock(batch, block)
  1253. }
  1254. stats.processed++
  1255. }
  1256. // Flush all tx-lookup index data.
  1257. size += batch.ValueSize()
  1258. if err := batch.Write(); err != nil {
  1259. return 0, err
  1260. }
  1261. batch.Reset()
  1262. // Sync the ancient store explicitly to ensure all data has been flushed to disk.
  1263. if err := bc.db.Sync(); err != nil {
  1264. return 0, err
  1265. }
  1266. if !updateHead(blockChain[len(blockChain)-1]) {
  1267. return 0, errors.New("side blocks can't be accepted as the ancient chain data")
  1268. }
  1269. previous = nil // disable rollback explicitly
  1270. // Wipe out canonical block data.
  1271. for _, nh := range deleted {
  1272. rawdb.DeleteBlockWithoutNumber(batch, nh.hash, nh.number)
  1273. rawdb.DeleteCanonicalHash(batch, nh.number)
  1274. }
  1275. for _, block := range blockChain {
  1276. // Always keep genesis block in active database.
  1277. if block.NumberU64() != 0 {
  1278. rawdb.DeleteBlockWithoutNumber(batch, block.Hash(), block.NumberU64())
  1279. rawdb.DeleteCanonicalHash(batch, block.NumberU64())
  1280. }
  1281. }
  1282. if err := batch.Write(); err != nil {
  1283. return 0, err
  1284. }
  1285. batch.Reset()
  1286. // Wipe out side chain too.
  1287. for _, nh := range deleted {
  1288. for _, hash := range rawdb.ReadAllHashes(bc.db, nh.number) {
  1289. rawdb.DeleteBlock(batch, hash, nh.number)
  1290. }
  1291. }
  1292. for _, block := range blockChain {
  1293. // Always keep genesis block in active database.
  1294. if block.NumberU64() != 0 {
  1295. for _, hash := range rawdb.ReadAllHashes(bc.db, block.NumberU64()) {
  1296. rawdb.DeleteBlock(batch, hash, block.NumberU64())
  1297. }
  1298. }
  1299. }
  1300. if err := batch.Write(); err != nil {
  1301. return 0, err
  1302. }
  1303. return 0, nil
  1304. }
  1305. // writeLive writes blockchain and corresponding receipt chain into active store.
  1306. writeLive := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  1307. skipPresenceCheck := false
  1308. batch := bc.db.NewBatch()
  1309. for i, block := range blockChain {
  1310. // Short circuit insertion if shutting down or processing failed
  1311. if bc.insertStopped() {
  1312. return 0, errInsertionInterrupted
  1313. }
  1314. // Short circuit if the owner header is unknown
  1315. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  1316. return i, fmt.Errorf("containing header #%d [%x..] unknown", block.Number(), block.Hash().Bytes()[:4])
  1317. }
  1318. if !skipPresenceCheck {
  1319. // Ignore if the entire data is already known
  1320. if bc.HasBlock(block.Hash(), block.NumberU64()) {
  1321. stats.ignored++
  1322. continue
  1323. } else {
  1324. // If block N is not present, neither are the later blocks.
  1325. // This should be true, but if we are mistaken, the shortcut
  1326. // here will only cause overwriting of some existing data
  1327. skipPresenceCheck = true
  1328. }
  1329. }
  1330. // Write all the data out into the database
  1331. rawdb.WriteBody(batch, block.Hash(), block.NumberU64(), block.Body())
  1332. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receiptChain[i])
  1333. rawdb.WriteTxLookupEntriesByBlock(batch, block) // Always write tx indices for live blocks, we assume they are needed
  1334. // Write everything belongs to the blocks into the database. So that
  1335. // we can ensure all components of body is completed(body, receipts,
  1336. // tx indexes)
  1337. if batch.ValueSize() >= ethdb.IdealBatchSize {
  1338. if err := batch.Write(); err != nil {
  1339. return 0, err
  1340. }
  1341. size += batch.ValueSize()
  1342. batch.Reset()
  1343. }
  1344. stats.processed++
  1345. }
  1346. // Write everything belongs to the blocks into the database. So that
  1347. // we can ensure all components of body is completed(body, receipts,
  1348. // tx indexes)
  1349. if batch.ValueSize() > 0 {
  1350. size += batch.ValueSize()
  1351. if err := batch.Write(); err != nil {
  1352. return 0, err
  1353. }
  1354. }
  1355. updateHead(blockChain[len(blockChain)-1])
  1356. return 0, nil
  1357. }
  1358. // Write downloaded chain data and corresponding receipt chain data
  1359. if len(ancientBlocks) > 0 {
  1360. if n, err := writeAncient(ancientBlocks, ancientReceipts); err != nil {
  1361. if err == errInsertionInterrupted {
  1362. return 0, nil
  1363. }
  1364. return n, err
  1365. }
  1366. }
  1367. // Write the tx index tail (block number from where we index) before write any live blocks
  1368. if len(liveBlocks) > 0 && liveBlocks[0].NumberU64() == ancientLimit+1 {
  1369. // The tx index tail can only be one of the following two options:
  1370. // * 0: all ancient blocks have been indexed
  1371. // * ancient-limit: the indices of blocks before ancient-limit are ignored
  1372. if tail := rawdb.ReadTxIndexTail(bc.db); tail == nil {
  1373. if bc.txLookupLimit == 0 || ancientLimit <= bc.txLookupLimit {
  1374. rawdb.WriteTxIndexTail(bc.db, 0)
  1375. } else {
  1376. rawdb.WriteTxIndexTail(bc.db, ancientLimit-bc.txLookupLimit)
  1377. }
  1378. }
  1379. }
  1380. if len(liveBlocks) > 0 {
  1381. if n, err := writeLive(liveBlocks, liveReceipts); err != nil {
  1382. if err == errInsertionInterrupted {
  1383. return 0, nil
  1384. }
  1385. return n, err
  1386. }
  1387. }
  1388. head := blockChain[len(blockChain)-1]
  1389. context := []interface{}{
  1390. "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  1391. "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(int64(head.Time()), 0)),
  1392. "size", common.StorageSize(size),
  1393. }
  1394. if stats.ignored > 0 {
  1395. context = append(context, []interface{}{"ignored", stats.ignored}...)
  1396. }
  1397. log.Info("Imported new block receipts", context...)
  1398. return 0, nil
  1399. }
  1400. // SetTxLookupLimit is responsible for updating the txlookup limit to the
  1401. // original one stored in db if the new mismatches with the old one.
  1402. func (bc *BlockChain) SetTxLookupLimit(limit uint64) {
  1403. bc.txLookupLimit = limit
  1404. }
  1405. // TxLookupLimit retrieves the txlookup limit used by blockchain to prune
  1406. // stale transaction indices.
  1407. func (bc *BlockChain) TxLookupLimit() uint64 {
  1408. return bc.txLookupLimit
  1409. }
  1410. var lastWrite uint64
  1411. // writeBlockWithoutState writes only the block and its metadata to the database,
  1412. // but does not write any state. This is used to construct competing side forks
  1413. // up to the point where they exceed the canonical total difficulty.
  1414. func (bc *BlockChain) writeBlockWithoutState(block *types.Block, td *big.Int) (err error) {
  1415. bc.wg.Add(1)
  1416. defer bc.wg.Done()
  1417. batch := bc.db.NewBatch()
  1418. rawdb.WriteTd(batch, block.Hash(), block.NumberU64(), td)
  1419. rawdb.WriteBlock(batch, block)
  1420. if err := batch.Write(); err != nil {
  1421. log.Crit("Failed to write block into disk", "err", err)
  1422. }
  1423. return nil
  1424. }
  1425. // writeKnownBlock updates the head block flag with a known block
  1426. // and introduces chain reorg if necessary.
  1427. func (bc *BlockChain) writeKnownBlock(block *types.Block) error {
  1428. bc.wg.Add(1)
  1429. defer bc.wg.Done()
  1430. current := bc.CurrentBlock()
  1431. if block.ParentHash() != current.Hash() {
  1432. if err := bc.reorg(current, block); err != nil {
  1433. return err
  1434. }
  1435. }
  1436. bc.writeHeadBlock(block)
  1437. return nil
  1438. }
  1439. // WriteBlockWithState writes the block and all associated state to the database.
  1440. func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, logs []*types.Log, state *state.StateDB, psManager mps.PrivateStateRepository, emitHeadEvent bool) (status WriteStatus, err error) {
  1441. bc.chainmu.Lock()
  1442. defer bc.chainmu.Unlock()
  1443. return bc.writeBlockWithState(block, receipts, logs, state, psManager, emitHeadEvent)
  1444. }
  1445. // QUORUM
  1446. // checks if the consensus engine is Rfat
  1447. func (bc *BlockChain) isRaft() bool {
  1448. return bc.chainConfig.IsQuorum && bc.chainConfig.Istanbul == nil && bc.chainConfig.IBFT == nil && bc.chainConfig.QBFT == nil && bc.chainConfig.Clique == nil
  1449. }
  1450. // function specifically added for Raft consensus. This is called from mintNewBlock
  1451. // to commit public and private state using bc.chainmu lock
  1452. // added to avoid concurrent map errors in high stress conditions
  1453. func (bc *BlockChain) CommitBlockWithState(deleteEmptyObjects bool, state, privateState *state.StateDB) error {
  1454. // check if consensus is not Raft
  1455. if !bc.isRaft() {
  1456. return errors.New("error function can be called only for Raft consensus")
  1457. }
  1458. bc.chainmu.Lock()
  1459. defer bc.chainmu.Unlock()
  1460. if _, err := state.Commit(deleteEmptyObjects); err != nil {
  1461. return fmt.Errorf("error committing public state: %v", err)
  1462. }
  1463. if _, err := privateState.Commit(deleteEmptyObjects); err != nil {
  1464. return fmt.Errorf("error committing private state: %v", err)
  1465. }
  1466. return nil
  1467. }
  1468. // END QUORUM
  1469. // writeBlockWithState writes the block and all associated state to the database,
  1470. // but is expects the chain mutex to be held.
  1471. func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.Receipt, logs []*types.Log, state *state.StateDB, psManager mps.PrivateStateRepository, emitHeadEvent bool) (status WriteStatus, err error) {
  1472. bc.wg.Add(1)
  1473. defer bc.wg.Done()
  1474. // Calculate the total difficulty of the block
  1475. ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1476. if ptd == nil {
  1477. return NonStatTy, consensus.ErrUnknownAncestor
  1478. }
  1479. currentBlock := bc.CurrentBlock()
  1480. localTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  1481. externTd := new(big.Int).Add(block.Difficulty(), ptd)
  1482. // Irrelevant of the canonical status, write the block itself to the database.
  1483. //
  1484. // Note all the components of block(td, hash->number map, header, body, receipts)
  1485. // should be written atomically. BlockBatch is used for containing all components.
  1486. blockBatch := bc.db.NewBatch()
  1487. rawdb.WriteTd(blockBatch, block.Hash(), block.NumberU64(), externTd)
  1488. rawdb.WriteBlock(blockBatch, block)
  1489. rawdb.WriteReceipts(blockBatch, block.Hash(), block.NumberU64(), receipts)
  1490. rawdb.WritePreimages(blockBatch, state.Preimages())
  1491. if err := blockBatch.Write(); err != nil {
  1492. log.Crit("Failed to write block into disk", "err", err)
  1493. }
  1494. // Commit all cached state changes into underlying memory database.
  1495. root, err := state.Commit(bc.chainConfig.IsEIP158(block.Number()))
  1496. if err != nil {
  1497. return NonStatTy, err
  1498. }
  1499. // quorum - private state commit must come after public state commit. If the private state is being cached then the
  1500. // private state root will reference the public state root, hence the need for public state trie to have already
  1501. // been committed.
  1502. // Make sure no inconsistent state is leaked during insertion
  1503. // Quorum
  1504. // Write private state changes to database
  1505. err = psManager.CommitAndWrite(bc.chainConfig.IsEIP158(block.Number()), block)
  1506. if err != nil {
  1507. return NonStatTy, err
  1508. }
  1509. if bc.privateStateRootHashValidator != nil {
  1510. err = bc.privateStateRootHashValidator.ValidatePrivateStateRoot(block.Hash(), block.Root())
  1511. if err != nil {
  1512. return NonStatTy, err
  1513. }
  1514. }
  1515. // /Quorum
  1516. triedb := bc.stateCache.TrieDB()
  1517. // If we're running an archive node, always flush
  1518. if bc.cacheConfig.TrieDirtyDisabled {
  1519. if err := triedb.Commit(root, false, nil); err != nil {
  1520. return NonStatTy, err
  1521. }
  1522. } else {
  1523. // Full but not archive node, do proper garbage collection
  1524. triedb.Reference(root, common.Hash{}) // metadata reference to keep trie alive
  1525. bc.triegc.Push(root, -int64(block.NumberU64()))
  1526. if current := block.NumberU64(); current > TriesInMemory {
  1527. // If we exceeded our memory allowance, flush matured singleton nodes to disk
  1528. var (
  1529. nodes, imgs = triedb.Size()
  1530. limit = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * 1024 * 1024
  1531. )
  1532. if nodes > limit || imgs > 4*1024*1024 {
  1533. triedb.Cap(limit - ethdb.IdealBatchSize)
  1534. }
  1535. // Find the next state trie we need to commit
  1536. chosen := current - TriesInMemory
  1537. // If we exceeded out time allowance, flush an entire trie to disk
  1538. if bc.gcproc > bc.cacheConfig.TrieTimeLimit {
  1539. // If the header is missing (canonical chain behind), we're reorging a low
  1540. // diff sidechain. Suspend committing until this operation is completed.
  1541. header := bc.GetHeaderByNumber(chosen)
  1542. if header == nil {
  1543. log.Warn("Reorg in progress, trie commit postponed", "number", chosen)
  1544. } else {
  1545. // If we're exceeding limits but haven't reached a large enough memory gap,
  1546. // warn the user that the system is becoming unstable.
  1547. if chosen < lastWrite+TriesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
  1548. log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/TriesInMemory)
  1549. }
  1550. // Flush an entire trie and restart the counters
  1551. triedb.Commit(header.Root, true, nil)
  1552. lastWrite = chosen
  1553. bc.gcproc = 0
  1554. }
  1555. }
  1556. // Garbage collect anything below our required write retention
  1557. for !bc.triegc.Empty() {
  1558. root, number := bc.triegc.Pop()
  1559. if uint64(-number) > chosen {
  1560. bc.triegc.Push(root, number)
  1561. break
  1562. }
  1563. triedb.Dereference(root.(common.Hash))
  1564. }
  1565. }
  1566. }
  1567. // If the total difficulty is higher than our known, add it to the canonical chain
  1568. // Second clause in the if statement reduces the vulnerability to selfish mining.
  1569. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  1570. reorg := externTd.Cmp(localTd) > 0
  1571. currentBlock = bc.CurrentBlock()
  1572. if !reorg && externTd.Cmp(localTd) == 0 {
  1573. // Split same-difficulty blocks by number, then preferentially select
  1574. // the block generated by the local miner as the canonical block.
  1575. if block.NumberU64() < currentBlock.NumberU64() {
  1576. reorg = true
  1577. } else if block.NumberU64() == currentBlock.NumberU64() {
  1578. var currentPreserve, blockPreserve bool
  1579. if bc.shouldPreserve != nil {
  1580. currentPreserve, blockPreserve = bc.shouldPreserve(currentBlock), bc.shouldPreserve(block)
  1581. }
  1582. reorg = !currentPreserve && (blockPreserve || mrand.Float64() < 0.5)
  1583. }
  1584. }
  1585. if reorg {
  1586. // Reorganise the chain if the parent is not the head block
  1587. if block.ParentHash() != currentBlock.Hash() {
  1588. if err := bc.reorg(currentBlock, block); err != nil {
  1589. return NonStatTy, err
  1590. }
  1591. }
  1592. status = CanonStatTy
  1593. } else {
  1594. status = SideStatTy
  1595. }
  1596. // Set new head.
  1597. if status == CanonStatTy {
  1598. bc.writeHeadBlock(block)
  1599. }
  1600. bc.futureBlocks.Remove(block.Hash())
  1601. if status == CanonStatTy {
  1602. bc.chainFeed.Send(ChainEvent{Block: block, Hash: block.Hash(), Logs: logs})
  1603. if len(logs) > 0 {
  1604. bc.logsFeed.Send(logs)
  1605. }
  1606. // In theory we should fire a ChainHeadEvent when we inject
  1607. // a canonical block, but sometimes we can insert a batch of
  1608. // canonicial blocks. Avoid firing too much ChainHeadEvents,
  1609. // we will fire an accumulated ChainHeadEvent and disable fire
  1610. // event here.
  1611. if emitHeadEvent {
  1612. bc.chainHeadFeed.Send(ChainHeadEvent{Block: block})
  1613. }
  1614. } else {
  1615. bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1616. }
  1617. return status, nil
  1618. }
  1619. // addFutureBlock checks if the block is within the max allowed window to get
  1620. // accepted for future processing, and returns an error if the block is too far
  1621. // ahead and was not added.
  1622. func (bc *BlockChain) addFutureBlock(block *types.Block) error {
  1623. max := uint64(time.Now().Unix() + maxTimeFutureBlocks)
  1624. if block.Time() > max {
  1625. return fmt.Errorf("future block timestamp %v > allowed %v", block.Time(), max)
  1626. }
  1627. bc.futureBlocks.Add(block.Hash(), block)
  1628. return nil
  1629. }
  1630. // InsertChain attempts to insert the given batch of blocks in to the canonical
  1631. // chain or, otherwise, create a fork. If an error is returned it will return
  1632. // the index number of the failing block as well an error describing what went
  1633. // wrong.
  1634. //
  1635. // After insertion is done, all accumulated events will be fired.
  1636. func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  1637. // Sanity check that we have something meaningful to import
  1638. if len(chain) == 0 {
  1639. return 0, nil
  1640. }
  1641. bc.blockProcFeed.Send(true)
  1642. defer bc.blockProcFeed.Send(false)
  1643. // Remove already known canon-blocks
  1644. var (
  1645. block, prev *types.Block
  1646. )
  1647. // Do a sanity check that the provided chain is actually ordered and linked
  1648. for i := 1; i < len(chain); i++ {
  1649. block = chain[i]
  1650. prev = chain[i-1]
  1651. if block.NumberU64() != prev.NumberU64()+1 || block.ParentHash() != prev.Hash() {
  1652. // Chain broke ancestry, log a message (programming error) and skip insertion
  1653. log.Error("Non contiguous block insert", "number", block.Number(), "hash", block.Hash(),
  1654. "parent", block.ParentHash(), "prevnumber", prev.Number(), "prevhash", prev.Hash())
  1655. return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x..], item %d is #%d [%x..] (parent [%x..])", i-1, prev.NumberU64(),
  1656. prev.Hash().Bytes()[:4], i, block.NumberU64(), block.Hash().Bytes()[:4], block.ParentHash().Bytes()[:4])
  1657. }
  1658. }
  1659. // Pre-checks passed, start the full block imports
  1660. bc.wg.Add(1)
  1661. bc.chainmu.Lock()
  1662. n, err := bc.insertChain(chain, true)
  1663. bc.chainmu.Unlock()
  1664. bc.wg.Done()
  1665. return n, err
  1666. }
  1667. // InsertChainWithoutSealVerification works exactly the same
  1668. // except for seal verification, seal verification is omitted
  1669. func (bc *BlockChain) InsertChainWithoutSealVerification(block *types.Block) (int, error) {
  1670. bc.blockProcFeed.Send(true)
  1671. defer bc.blockProcFeed.Send(false)
  1672. // Pre-checks passed, start the full block imports
  1673. bc.wg.Add(1)
  1674. bc.chainmu.Lock()
  1675. n, err := bc.insertChain(types.Blocks([]*types.Block{block}), false)
  1676. bc.chainmu.Unlock()
  1677. bc.wg.Done()
  1678. return n, err
  1679. }
  1680. // insertChain is the internal implementation of InsertChain, which assumes that
  1681. // 1) chains are contiguous, and 2) The chain mutex is held.
  1682. //
  1683. // This method is split out so that import batches that require re-injecting
  1684. // historical blocks can do so without releasing the lock, which could lead to
  1685. // racey behaviour. If a sidechain import is in progress, and the historic state
  1686. // is imported, but then new canon-head is added before the actual sidechain
  1687. // completes, then the historic state could be pruned again
  1688. func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, error) {
  1689. // If the chain is terminating, don't even bother starting up
  1690. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1691. log.Debug("Premature abort during blocks processing")
  1692. // QUORUM
  1693. if bc.isRaft() {
  1694. // Only returns an error for raft mode
  1695. return 0, ErrAbortBlocksProcessing
  1696. }
  1697. return 0, nil
  1698. }
  1699. // Start a parallel signature recovery (signer will fluke on fork transition, minimal perf loss)
  1700. senderCacher.recoverFromBlocks(types.MakeSigner(bc.chainConfig, chain[0].Number()), chain)
  1701. var (
  1702. stats = insertStats{startTime: mclock.Now()}
  1703. lastCanon *types.Block
  1704. )
  1705. // Fire a single chain head event if we've progressed the chain
  1706. defer func() {
  1707. if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() {
  1708. bc.chainHeadFeed.Send(ChainHeadEvent{lastCanon})
  1709. }
  1710. }()
  1711. // Start the parallel header verifier
  1712. headers := make([]*types.Header, len(chain))
  1713. seals := make([]bool, len(chain))
  1714. for i, block := range chain {
  1715. headers[i] = block.Header()
  1716. seals[i] = verifySeals
  1717. }
  1718. abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
  1719. defer close(abort)
  1720. // Peek the error for the first block to decide the directing import logic
  1721. it := newInsertIterator(chain, results, bc.validator)
  1722. block, err := it.next()
  1723. // Left-trim all the known blocks
  1724. if err == ErrKnownBlock {
  1725. // First block (and state) is known
  1726. // 1. We did a roll-back, and should now do a re-import
  1727. // 2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
  1728. // from the canonical chain, which has not been verified.
  1729. // Skip all known blocks that are behind us
  1730. var (
  1731. current = bc.CurrentBlock()
  1732. localTd = bc.GetTd(current.Hash(), current.NumberU64())
  1733. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1) // The first block can't be nil
  1734. )
  1735. for block != nil && err == ErrKnownBlock {
  1736. externTd = new(big.Int).Add(externTd, block.Difficulty())
  1737. if localTd.Cmp(externTd) < 0 {
  1738. break
  1739. }
  1740. log.Debug("Ignoring already known block", "number", block.Number(), "hash", block.Hash())
  1741. stats.ignored++
  1742. block, err = it.next()
  1743. }
  1744. // The remaining blocks are still known blocks, the only scenario here is:
  1745. // During the fast sync, the pivot point is already submitted but rollback
  1746. // happens. Then node resets the head full block to a lower height via `rollback`
  1747. // and leaves a few known blocks in the database.
  1748. //
  1749. // When node runs a fast sync again, it can re-import a batch of known blocks via
  1750. // `insertChain` while a part of them have higher total difficulty than current
  1751. // head full block(new pivot point).
  1752. for block != nil && err == ErrKnownBlock {
  1753. log.Debug("Writing previously known block", "number", block.Number(), "hash", block.Hash())
  1754. if err := bc.writeKnownBlock(block); err != nil {
  1755. return it.index, err
  1756. }
  1757. lastCanon = block
  1758. block, err = it.next()
  1759. }
  1760. // Falls through to the block import
  1761. }
  1762. switch {
  1763. // First block is pruned, insert as sidechain and reorg only if TD grows enough
  1764. case errors.Is(err, consensus.ErrPrunedAncestor):
  1765. log.Debug("Pruned ancestor, inserting as sidechain", "number", block.Number(), "hash", block.Hash())
  1766. return bc.insertSideChain(block, it)
  1767. // First block is future, shove it (and all children) to the future queue (unknown ancestor)
  1768. case errors.Is(err, consensus.ErrFutureBlock) || (errors.Is(err, consensus.ErrUnknownAncestor) && bc.futureBlocks.Contains(it.first().ParentHash())):
  1769. for block != nil && (it.index == 0 || errors.Is(err, consensus.ErrUnknownAncestor)) {
  1770. log.Debug("Future block, postponing import", "number", block.Number(), "hash", block.Hash())
  1771. if err := bc.addFutureBlock(block); err != nil {
  1772. return it.index, err
  1773. }
  1774. block, err = it.next()
  1775. }
  1776. stats.queued += it.processed()
  1777. stats.ignored += it.remaining()
  1778. // If there are any still remaining, mark as ignored
  1779. return it.index, err
  1780. // Some other error occurred, abort
  1781. case err != nil:
  1782. bc.futureBlocks.Remove(block.Hash())
  1783. stats.ignored += len(it.chain)
  1784. bc.reportBlock(block, nil, err)
  1785. return it.index, err
  1786. }
  1787. // No validation errors for the first block (or chain prefix skipped)
  1788. var activeState *state.StateDB
  1789. defer func() {
  1790. // The chain importer is starting and stopping trie prefetchers. If a bad
  1791. // block or other error is hit however, an early return may not properly
  1792. // terminate the background threads. This defer ensures that we clean up
  1793. // and dangling prefetcher, without defering each and holding on live refs.
  1794. if activeState != nil {
  1795. activeState.StopPrefetcher()
  1796. }
  1797. }()
  1798. for ; block != nil && err == nil || err == ErrKnownBlock; block, err = it.next() {
  1799. // If the chain is terminating, stop processing blocks
  1800. if bc.insertStopped() {
  1801. log.Debug("Abort during block processing")
  1802. // QUORUM
  1803. if bc.isRaft() {
  1804. // Only returns an error for raft mode
  1805. return it.index, ErrAbortBlocksProcessing
  1806. }
  1807. // END QUORUM
  1808. break
  1809. }
  1810. // If the header is a banned one, straight out abort
  1811. if BadHashes[block.Hash()] {
  1812. bc.reportBlock(block, nil, ErrBlacklistedHash)
  1813. return it.index, ErrBlacklistedHash
  1814. }
  1815. // If the block is known (in the middle of the chain), it's a special case for
  1816. // Clique blocks where they can share state among each other, so importing an
  1817. // older block might complete the state of the subsequent one. In this case,
  1818. // just skip the block (we already validated it once fully (and crashed), since
  1819. // its header and body was already in the database).
  1820. if err == ErrKnownBlock {
  1821. logger := log.Debug
  1822. if bc.chainConfig.Clique == nil {
  1823. logger = log.Warn
  1824. }
  1825. logger("Inserted known block", "number", block.Number(), "hash", block.Hash(),
  1826. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1827. "root", block.Root())
  1828. // Special case. Commit the empty receipt slice if we meet the known
  1829. // block in the middle. It can only happen in the clique chain. Whenever
  1830. // we insert blocks via `insertSideChain`, we only commit `td`, `header`
  1831. // and `body` if it's non-existent. Since we don't have receipts without
  1832. // reexecution, so nothing to commit. But if the sidechain will be adpoted
  1833. // as the canonical chain eventually, it needs to be reexecuted for missing
  1834. // state, but if it's this special case here(skip reexecution) we will lose
  1835. // the empty receipt entry.
  1836. if len(block.Transactions()) == 0 {
  1837. rawdb.WriteReceipts(bc.db, block.Hash(), block.NumberU64(), nil)
  1838. } else {
  1839. log.Error("Please file an issue, skip known block execution without receipt",
  1840. "hash", block.Hash(), "number", block.NumberU64())
  1841. }
  1842. if err := bc.writeKnownBlock(block); err != nil {
  1843. return it.index, err
  1844. }
  1845. stats.processed++
  1846. // We can assume that logs are empty here, since the only way for consecutive
  1847. // Clique blocks to have the same state is if there are no transactions.
  1848. lastCanon = block
  1849. continue
  1850. }
  1851. // Retrieve the parent block and it's state to execute on top
  1852. start := time.Now()
  1853. parent := it.previous()
  1854. if parent == nil {
  1855. parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1)
  1856. }
  1857. statedb, err := state.New(parent.Root, bc.stateCache, bc.snaps)
  1858. if err != nil {
  1859. return it.index, err
  1860. }
  1861. // Quorum
  1862. privateStateRepo, err := bc.privateStateManager.StateRepository(parent.Root)
  1863. if err != nil {
  1864. return it.index, err
  1865. }
  1866. // End Quorum
  1867. // Enable prefetching to pull in trie node paths while processing transactions
  1868. statedb.StartPrefetcher("chain")
  1869. activeState = statedb
  1870. // If we have a followup block, run that against the current state to pre-cache
  1871. // transactions and probabilistically some of the account/storage trie nodes.
  1872. var followupInterrupt uint32
  1873. if !bc.cacheConfig.TrieCleanNoPrefetch {
  1874. if followup, err := it.peek(); followup != nil && err == nil {
  1875. throwaway, _ := state.New(parent.Root, bc.stateCache, bc.snaps)
  1876. // Quorum
  1877. privateStateRepo, stateRepoErr := bc.privateStateManager.StateRepository(parent.Root)
  1878. if stateRepoErr == nil && privateStateRepo != nil {
  1879. throwawayPrivateStateRepo := privateStateRepo.Copy()
  1880. // Quorum: add privateStateThrowaway argument
  1881. go func(start time.Time, followup *types.Block, throwaway *state.StateDB, privateStateThrowaway mps.PrivateStateRepository, interrupt *uint32) {
  1882. bc.prefetcher.Prefetch(followup, throwaway, throwawayPrivateStateRepo, bc.vmConfig, &followupInterrupt)
  1883. blockPrefetchExecuteTimer.Update(time.Since(start))
  1884. if atomic.LoadUint32(interrupt) == 1 {
  1885. blockPrefetchInterruptMeter.Mark(1)
  1886. }
  1887. }(time.Now(), followup, throwaway, throwawayPrivateStateRepo, &followupInterrupt)
  1888. } else {
  1889. log.Warn("Unable to load the private state repository for pre-fetching", "stateRepoErr", stateRepoErr)
  1890. }
  1891. // End Quorum
  1892. }
  1893. }
  1894. // Process block using the parent state as reference point
  1895. substart := time.Now()
  1896. receipts, privateReceipts, logs, usedGas, err := bc.processor.Process(block, statedb, privateStateRepo, bc.vmConfig)
  1897. if err != nil {
  1898. bc.reportBlock(block, receipts, err)
  1899. atomic.StoreUint32(&followupInterrupt, 1)
  1900. return it.index, err
  1901. }
  1902. // Update the metrics touched during block processing
  1903. accountReadTimer.Update(statedb.AccountReads) // Account reads are complete, we can mark them
  1904. storageReadTimer.Update(statedb.StorageReads) // Storage reads are complete, we can mark them
  1905. accountUpdateTimer.Update(statedb.AccountUpdates) // Account updates are complete, we can mark them
  1906. storageUpdateTimer.Update(statedb.StorageUpdates) // Storage updates are complete, we can mark them
  1907. snapshotAccountReadTimer.Update(statedb.SnapshotAccountReads) // Account reads are complete, we can mark them
  1908. snapshotStorageReadTimer.Update(statedb.SnapshotStorageReads) // Storage reads are complete, we can mark them
  1909. triehash := statedb.AccountHashes + statedb.StorageHashes // Save to not double count in validation
  1910. trieproc := statedb.SnapshotAccountReads + statedb.AccountReads + statedb.AccountUpdates
  1911. trieproc += statedb.SnapshotStorageReads + statedb.StorageReads + statedb.StorageUpdates
  1912. blockExecutionTimer.Update(time.Since(substart) - trieproc - triehash)
  1913. // Validate the state using the default validator
  1914. substart = time.Now()
  1915. if err := bc.validator.ValidateState(block, statedb, receipts, usedGas); err != nil {
  1916. bc.reportBlock(block, receipts, err)
  1917. atomic.StoreUint32(&followupInterrupt, 1)
  1918. return it.index, err
  1919. }
  1920. allReceipts := privateStateRepo.MergeReceipts(receipts, privateReceipts)
  1921. proctime := time.Since(start)
  1922. // Update the metrics touched during block validation
  1923. accountHashTimer.Update(statedb.AccountHashes) // Account hashes are complete, we can mark them
  1924. storageHashTimer.Update(statedb.StorageHashes) // Storage hashes are complete, we can mark them
  1925. blockValidationTimer.Update(time.Since(substart) - (statedb.AccountHashes + statedb.StorageHashes - triehash))
  1926. // Write the block to the chain and get the status.
  1927. substart = time.Now()
  1928. status, err := bc.writeBlockWithState(block, allReceipts, logs, statedb, privateStateRepo, false)
  1929. atomic.StoreUint32(&followupInterrupt, 1)
  1930. if err != nil {
  1931. return it.index, err
  1932. }
  1933. // Quorum
  1934. if err := rawdb.WritePrivateBlockBloom(bc.db, block.NumberU64(), privateReceipts); err != nil {
  1935. return it.index, err
  1936. }
  1937. // End Quorum
  1938. // Update the metrics touched during block commit
  1939. accountCommitTimer.Update(statedb.AccountCommits) // Account commits are complete, we can mark them
  1940. storageCommitTimer.Update(statedb.StorageCommits) // Storage commits are complete, we can mark them
  1941. snapshotCommitTimer.Update(statedb.SnapshotCommits) // Snapshot commits are complete, we can mark them
  1942. blockWriteTimer.Update(time.Since(substart) - statedb.AccountCommits - statedb.StorageCommits - statedb.SnapshotCommits)
  1943. blockInsertTimer.UpdateSince(start)
  1944. switch status {
  1945. case CanonStatTy:
  1946. log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(),
  1947. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1948. "elapsed", common.PrettyDuration(time.Since(start)),
  1949. "root", block.Root())
  1950. lastCanon = block
  1951. // Only count canonical blocks for GC processing time
  1952. bc.gcproc += proctime
  1953. case SideStatTy:
  1954. log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(),
  1955. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1956. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1957. "root", block.Root())
  1958. default:
  1959. // This in theory is impossible, but lets be nice to our future selves and leave
  1960. // a log, instead of trying to track down blocks imports that don't emit logs.
  1961. log.Warn("Inserted block with unknown status", "number", block.Number(), "hash", block.Hash(),
  1962. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1963. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1964. "root", block.Root())
  1965. }
  1966. stats.processed++
  1967. stats.usedGas += usedGas
  1968. dirty, _ := bc.stateCache.TrieDB().Size()
  1969. stats.report(chain, it.index, dirty)
  1970. }
  1971. // Any blocks remaining here? The only ones we care about are the future ones
  1972. if block != nil && errors.Is(err, consensus.ErrFutureBlock) {
  1973. if err := bc.addFutureBlock(block); err != nil {
  1974. return it.index, err
  1975. }
  1976. block, err = it.next()
  1977. for ; block != nil && errors.Is(err, consensus.ErrUnknownAncestor); block, err = it.next() {
  1978. if err := bc.addFutureBlock(block); err != nil {
  1979. return it.index, err
  1980. }
  1981. stats.queued++
  1982. }
  1983. }
  1984. stats.ignored += it.remaining()
  1985. return it.index, err
  1986. }
  1987. // insertSideChain is called when an import batch hits upon a pruned ancestor
  1988. // error, which happens when a sidechain with a sufficiently old fork-block is
  1989. // found.
  1990. //
  1991. // The method writes all (header-and-body-valid) blocks to disk, then tries to
  1992. // switch over to the new chain if the TD exceeded the current chain.
  1993. func (bc *BlockChain) insertSideChain(block *types.Block, it *insertIterator) (int, error) {
  1994. var (
  1995. externTd *big.Int
  1996. current = bc.CurrentBlock()
  1997. )
  1998. // The first sidechain block error is already verified to be ErrPrunedAncestor.
  1999. // Since we don't import them here, we expect ErrUnknownAncestor for the remaining
  2000. // ones. Any other errors means that the block is invalid, and should not be written
  2001. // to disk.
  2002. err := consensus.ErrPrunedAncestor
  2003. for ; block != nil && errors.Is(err, consensus.ErrPrunedAncestor); block, err = it.next() {
  2004. // Check the canonical state root for that number
  2005. if number := block.NumberU64(); current.NumberU64() >= number {
  2006. canonical := bc.GetBlockByNumber(number)
  2007. if canonical != nil && canonical.Hash() == block.Hash() {
  2008. // Not a sidechain block, this is a re-import of a canon block which has it's state pruned
  2009. // Collect the TD of the block. Since we know it's a canon one,
  2010. // we can get it directly, and not (like further below) use
  2011. // the parent and then add the block on top
  2012. externTd = bc.GetTd(block.Hash(), block.NumberU64())
  2013. continue
  2014. }
  2015. if canonical != nil && canonical.Root() == block.Root() {
  2016. // This is most likely a shadow-state attack. When a fork is imported into the
  2017. // database, and it eventually reaches a block height which is not pruned, we
  2018. // just found that the state already exist! This means that the sidechain block
  2019. // refers to a state which already exists in our canon chain.
  2020. //
  2021. // If left unchecked, we would now proceed importing the blocks, without actually
  2022. // having verified the state of the previous blocks.
  2023. log.Warn("Sidechain ghost-state attack detected", "number", block.NumberU64(), "sideroot", block.Root(), "canonroot", canonical.Root())
  2024. // If someone legitimately side-mines blocks, they would still be imported as usual. However,
  2025. // we cannot risk writing unverified blocks to disk when they obviously target the pruning
  2026. // mechanism.
  2027. return it.index, errors.New("sidechain ghost-state attack")
  2028. }
  2029. }
  2030. if externTd == nil {
  2031. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  2032. }
  2033. externTd = new(big.Int).Add(externTd, block.Difficulty())
  2034. if !bc.HasBlock(block.Hash(), block.NumberU64()) {
  2035. start := time.Now()
  2036. if err := bc.writeBlockWithoutState(block, externTd); err != nil {
  2037. return it.index, err
  2038. }
  2039. log.Debug("Injected sidechain block", "number", block.Number(), "hash", block.Hash(),
  2040. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  2041. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  2042. "root", block.Root())
  2043. }
  2044. }
  2045. // At this point, we've written all sidechain blocks to database. Loop ended
  2046. // either on some other error or all were processed. If there was some other
  2047. // error, we can ignore the rest of those blocks.
  2048. //
  2049. // If the externTd was larger than our local TD, we now need to reimport the previous
  2050. // blocks to regenerate the required state
  2051. localTd := bc.GetTd(current.Hash(), current.NumberU64())
  2052. if localTd.Cmp(externTd) > 0 {
  2053. log.Info("Sidechain written to disk", "start", it.first().NumberU64(), "end", it.previous().Number, "sidetd", externTd, "localtd", localTd)
  2054. return it.index, err
  2055. }
  2056. // Gather all the sidechain hashes (full blocks may be memory heavy)
  2057. var (
  2058. hashes []common.Hash
  2059. numbers []uint64
  2060. )
  2061. parent := it.previous()
  2062. for parent != nil && !bc.HasState(parent.Root) {
  2063. hashes = append(hashes, parent.Hash())
  2064. numbers = append(numbers, parent.Number.Uint64())
  2065. parent = bc.GetHeader(parent.ParentHash, parent.Number.Uint64()-1)
  2066. }
  2067. if parent == nil {
  2068. return it.index, errors.New("missing parent")
  2069. }
  2070. // Import all the pruned blocks to make the state available
  2071. var (
  2072. blocks []*types.Block
  2073. memory common.StorageSize
  2074. )
  2075. for i := len(hashes) - 1; i >= 0; i-- {
  2076. // Append the next block to our batch
  2077. block := bc.GetBlock(hashes[i], numbers[i])
  2078. blocks = append(blocks, block)
  2079. memory += block.Size()
  2080. // If memory use grew too large, import and continue. Sadly we need to discard
  2081. // all raised events and logs from notifications since we're too heavy on the
  2082. // memory here.
  2083. if len(blocks) >= 2048 || memory > 64*1024*1024 {
  2084. log.Info("Importing heavy sidechain segment", "blocks", len(blocks), "start", blocks[0].NumberU64(), "end", block.NumberU64())
  2085. if _, err := bc.insertChain(blocks, false); err != nil {
  2086. return 0, err
  2087. }
  2088. blocks, memory = blocks[:0], 0
  2089. // If the chain is terminating, stop processing blocks
  2090. if bc.insertStopped() {
  2091. log.Debug("Abort during blocks processing")
  2092. return 0, nil
  2093. }
  2094. }
  2095. }
  2096. if len(blocks) > 0 {
  2097. log.Info("Importing sidechain segment", "start", blocks[0].NumberU64(), "end", blocks[len(blocks)-1].NumberU64())
  2098. return bc.insertChain(blocks, false)
  2099. }
  2100. return 0, nil
  2101. }
  2102. // reorg takes two blocks, an old chain and a new chain and will reconstruct the
  2103. // blocks and inserts them to be part of the new canonical chain and accumulates
  2104. // potential missing transactions and post an event about them.
  2105. func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  2106. var (
  2107. newChain types.Blocks
  2108. oldChain types.Blocks
  2109. commonBlock *types.Block
  2110. deletedTxs types.Transactions
  2111. addedTxs types.Transactions
  2112. deletedLogs [][]*types.Log
  2113. rebirthLogs [][]*types.Log
  2114. // collectLogs collects the logs that were generated or removed during
  2115. // the processing of the block that corresponds with the given hash.
  2116. // These logs are later announced as deleted or reborn
  2117. collectLogs = func(hash common.Hash, removed bool) {
  2118. number := bc.hc.GetBlockNumber(hash)
  2119. if number == nil {
  2120. return
  2121. }
  2122. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  2123. var logs []*types.Log
  2124. for _, receipt := range receipts {
  2125. for _, log := range receipt.Logs {
  2126. l := *log
  2127. if removed {
  2128. l.Removed = true
  2129. }
  2130. logs = append(logs, &l)
  2131. }
  2132. }
  2133. if len(logs) > 0 {
  2134. if removed {
  2135. deletedLogs = append(deletedLogs, logs)
  2136. } else {
  2137. rebirthLogs = append(rebirthLogs, logs)
  2138. }
  2139. }
  2140. }
  2141. // mergeLogs returns a merged log slice with specified sort order.
  2142. mergeLogs = func(logs [][]*types.Log, reverse bool) []*types.Log {
  2143. var ret []*types.Log
  2144. if reverse {
  2145. for i := len(logs) - 1; i >= 0; i-- {
  2146. ret = append(ret, logs[i]...)
  2147. }
  2148. } else {
  2149. for i := 0; i < len(logs); i++ {
  2150. ret = append(ret, logs[i]...)
  2151. }
  2152. }
  2153. return ret
  2154. }
  2155. )
  2156. // Reduce the longer chain to the same number as the shorter one
  2157. if oldBlock.NumberU64() > newBlock.NumberU64() {
  2158. // Old chain is longer, gather all transactions and logs as deleted ones
  2159. for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  2160. oldChain = append(oldChain, oldBlock)
  2161. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  2162. collectLogs(oldBlock.Hash(), true)
  2163. }
  2164. } else {
  2165. // New chain is longer, stash all blocks away for subsequent insertion
  2166. for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  2167. newChain = append(newChain, newBlock)
  2168. }
  2169. }
  2170. if oldBlock == nil {
  2171. return fmt.Errorf("invalid old chain")
  2172. }
  2173. if newBlock == nil {
  2174. return fmt.Errorf("invalid new chain")
  2175. }
  2176. // Both sides of the reorg are at the same number, reduce both until the common
  2177. // ancestor is found
  2178. for {
  2179. // If the common ancestor was found, bail out
  2180. if oldBlock.Hash() == newBlock.Hash() {
  2181. commonBlock = oldBlock
  2182. break
  2183. }
  2184. // Remove an old block as well as stash away a new block
  2185. oldChain = append(oldChain, oldBlock)
  2186. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  2187. collectLogs(oldBlock.Hash(), true)
  2188. newChain = append(newChain, newBlock)
  2189. // Step back with both chains
  2190. oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1)
  2191. if oldBlock == nil {
  2192. return fmt.Errorf("invalid old chain")
  2193. }
  2194. newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  2195. if newBlock == nil {
  2196. return fmt.Errorf("invalid new chain")
  2197. }
  2198. }
  2199. // Ensure the user sees large reorgs
  2200. if len(oldChain) > 0 && len(newChain) > 0 {
  2201. logFn := log.Info
  2202. msg := "Chain reorg detected"
  2203. if len(oldChain) > 63 {
  2204. msg = "Large chain reorg detected"
  2205. logFn = log.Warn
  2206. }
  2207. logFn(msg, "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  2208. "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  2209. blockReorgAddMeter.Mark(int64(len(newChain)))
  2210. blockReorgDropMeter.Mark(int64(len(oldChain)))
  2211. blockReorgMeter.Mark(1)
  2212. } else {
  2213. log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  2214. }
  2215. // Insert the new chain(except the head block(reverse order)),
  2216. // taking care of the proper incremental order.
  2217. for i := len(newChain) - 1; i >= 1; i-- {
  2218. // Insert the block in the canonical way, re-writing history
  2219. bc.writeHeadBlock(newChain[i])
  2220. // Collect reborn logs due to chain reorg
  2221. collectLogs(newChain[i].Hash(), false)
  2222. // Collect the new added transactions.
  2223. addedTxs = append(addedTxs, newChain[i].Transactions()...)
  2224. }
  2225. // Delete useless indexes right now which includes the non-canonical
  2226. // transaction indexes, canonical chain indexes which above the head.
  2227. indexesBatch := bc.db.NewBatch()
  2228. for _, tx := range types.TxDifference(deletedTxs, addedTxs) {
  2229. rawdb.DeleteTxLookupEntry(indexesBatch, tx.Hash())
  2230. }
  2231. // Delete any canonical number assignments above the new head
  2232. number := bc.CurrentBlock().NumberU64()
  2233. for i := number + 1; ; i++ {
  2234. hash := rawdb.ReadCanonicalHash(bc.db, i)
  2235. if hash == (common.Hash{}) {
  2236. break
  2237. }
  2238. rawdb.DeleteCanonicalHash(indexesBatch, i)
  2239. }
  2240. if err := indexesBatch.Write(); err != nil {
  2241. log.Crit("Failed to delete useless indexes", "err", err)
  2242. }
  2243. // If any logs need to be fired, do it now. In theory we could avoid creating
  2244. // this goroutine if there are no events to fire, but realistcally that only
  2245. // ever happens if we're reorging empty blocks, which will only happen on idle
  2246. // networks where performance is not an issue either way.
  2247. if len(deletedLogs) > 0 {
  2248. bc.rmLogsFeed.Send(RemovedLogsEvent{mergeLogs(deletedLogs, true)})
  2249. }
  2250. if len(rebirthLogs) > 0 {
  2251. bc.logsFeed.Send(mergeLogs(rebirthLogs, false))
  2252. }
  2253. if len(oldChain) > 0 {
  2254. for i := len(oldChain) - 1; i >= 0; i-- {
  2255. bc.chainSideFeed.Send(ChainSideEvent{Block: oldChain[i]})
  2256. }
  2257. }
  2258. return nil
  2259. }
  2260. func (bc *BlockChain) update() {
  2261. futureTimer := time.NewTicker(5 * time.Second)
  2262. defer futureTimer.Stop()
  2263. for {
  2264. select {
  2265. case <-futureTimer.C:
  2266. bc.procFutureBlocks()
  2267. case <-bc.quit:
  2268. return
  2269. }
  2270. }
  2271. }
  2272. // maintainTxIndex is responsible for the construction and deletion of the
  2273. // transaction index.
  2274. //
  2275. // User can use flag `txlookuplimit` to specify a "recentness" block, below
  2276. // which ancient tx indices get deleted. If `txlookuplimit` is 0, it means
  2277. // all tx indices will be reserved.
  2278. //
  2279. // The user can adjust the txlookuplimit value for each launch after fast
  2280. // sync, Geth will automatically construct the missing indices and delete
  2281. // the extra indices.
  2282. func (bc *BlockChain) maintainTxIndex(ancients uint64) {
  2283. defer bc.wg.Done()
  2284. // Before starting the actual maintenance, we need to handle a special case,
  2285. // where user might init Geth with an external ancient database. If so, we
  2286. // need to reindex all necessary transactions before starting to process any
  2287. // pruning requests.
  2288. if ancients > 0 {
  2289. var from = uint64(0)
  2290. if bc.txLookupLimit != 0 && ancients > bc.txLookupLimit {
  2291. from = ancients - bc.txLookupLimit
  2292. }
  2293. rawdb.IndexTransactions(bc.db, from, ancients, bc.quit)
  2294. }
  2295. // indexBlocks reindexes or unindexes transactions depending on user configuration
  2296. indexBlocks := func(tail *uint64, head uint64, done chan struct{}) {
  2297. defer func() { done <- struct{}{} }()
  2298. // If the user just upgraded Geth to a new version which supports transaction
  2299. // index pruning, write the new tail and remove anything older.
  2300. if tail == nil {
  2301. if bc.txLookupLimit == 0 || head < bc.txLookupLimit {
  2302. // Nothing to delete, write the tail and return
  2303. rawdb.WriteTxIndexTail(bc.db, 0)
  2304. } else {
  2305. // Prune all stale tx indices and record the tx index tail
  2306. rawdb.UnindexTransactions(bc.db, 0, head-bc.txLookupLimit+1, bc.quit)
  2307. }
  2308. return
  2309. }
  2310. // If a previous indexing existed, make sure that we fill in any missing entries
  2311. if bc.txLookupLimit == 0 || head < bc.txLookupLimit {
  2312. if *tail > 0 {
  2313. rawdb.IndexTransactions(bc.db, 0, *tail, bc.quit)
  2314. }
  2315. return
  2316. }
  2317. // Update the transaction index to the new chain state
  2318. if head-bc.txLookupLimit+1 < *tail {
  2319. // Reindex a part of missing indices and rewind index tail to HEAD-limit
  2320. rawdb.IndexTransactions(bc.db, head-bc.txLookupLimit+1, *tail, bc.quit)
  2321. } else {
  2322. // Unindex a part of stale indices and forward index tail to HEAD-limit
  2323. rawdb.UnindexTransactions(bc.db, *tail, head-bc.txLookupLimit+1, bc.quit)
  2324. }
  2325. }
  2326. // Any reindexing done, start listening to chain events and moving the index window
  2327. var (
  2328. done chan struct{} // Non-nil if background unindexing or reindexing routine is active.
  2329. headCh = make(chan ChainHeadEvent, 1) // Buffered to avoid locking up the event feed
  2330. )
  2331. sub := bc.SubscribeChainHeadEvent(headCh)
  2332. if sub == nil {
  2333. return
  2334. }
  2335. defer sub.Unsubscribe()
  2336. for {
  2337. select {
  2338. case head := <-headCh:
  2339. if done == nil {
  2340. done = make(chan struct{})
  2341. go indexBlocks(rawdb.ReadTxIndexTail(bc.db), head.Block.NumberU64(), done)
  2342. }
  2343. case <-done:
  2344. done = nil
  2345. case <-bc.quit:
  2346. if done != nil {
  2347. log.Info("Waiting background transaction indexer to exit")
  2348. <-done
  2349. }
  2350. return
  2351. }
  2352. }
  2353. }
  2354. // reportBlock logs a bad block error.
  2355. func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  2356. rawdb.WriteBadBlock(bc.db, block)
  2357. var receiptString string
  2358. for i, receipt := range receipts {
  2359. receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n",
  2360. i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(),
  2361. receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState)
  2362. }
  2363. log.Error(fmt.Sprintf(`
  2364. ########## BAD BLOCK #########
  2365. Chain config: %v
  2366. Number: %v
  2367. Hash: 0x%x
  2368. %v
  2369. Error: %v
  2370. ##############################
  2371. `, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
  2372. }
  2373. // InsertHeaderChain attempts to insert the given header chain in to the local
  2374. // chain, possibly creating a reorg. If an error is returned, it will return the
  2375. // index number of the failing header as well an error describing what went wrong.
  2376. //
  2377. // The verify parameter can be used to fine tune whether nonce verification
  2378. // should be done or not. The reason behind the optional check is because some
  2379. // of the header retrieval mechanisms already need to verify nonces, as well as
  2380. // because nonces can be verified sparsely, not needing to check each.
  2381. func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  2382. start := time.Now()
  2383. if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  2384. return i, err
  2385. }
  2386. // Make sure only one thread manipulates the chain at once
  2387. bc.chainmu.Lock()
  2388. defer bc.chainmu.Unlock()
  2389. bc.wg.Add(1)
  2390. defer bc.wg.Done()
  2391. _, err := bc.hc.InsertHeaderChain(chain, start)
  2392. return 0, err
  2393. }
  2394. // CurrentHeader retrieves the current head header of the canonical chain. The
  2395. // header is retrieved from the HeaderChain's internal cache.
  2396. func (bc *BlockChain) CurrentHeader() *types.Header {
  2397. return bc.hc.CurrentHeader()
  2398. }
  2399. // GetTd retrieves a block's total difficulty in the canonical chain from the
  2400. // database by hash and number, caching it if found.
  2401. func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  2402. return bc.hc.GetTd(hash, number)
  2403. }
  2404. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  2405. // database by hash, caching it if found.
  2406. func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  2407. return bc.hc.GetTdByHash(hash)
  2408. }
  2409. // GetHeader retrieves a block header from the database by hash and number,
  2410. // caching it if found.
  2411. func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  2412. return bc.hc.GetHeader(hash, number)
  2413. }
  2414. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  2415. // found.
  2416. func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  2417. return bc.hc.GetHeaderByHash(hash)
  2418. }
  2419. // HasHeader checks if a block header is present in the database or not, caching
  2420. // it if present.
  2421. func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  2422. return bc.hc.HasHeader(hash, number)
  2423. }
  2424. // GetCanonicalHash returns the canonical hash for a given block number
  2425. func (bc *BlockChain) GetCanonicalHash(number uint64) common.Hash {
  2426. return bc.hc.GetCanonicalHash(number)
  2427. }
  2428. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  2429. // hash, fetching towards the genesis block.
  2430. func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  2431. return bc.hc.GetBlockHashesFromHash(hash, max)
  2432. }
  2433. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  2434. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  2435. // number of blocks to be individually checked before we reach the canonical chain.
  2436. //
  2437. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  2438. func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  2439. return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  2440. }
  2441. // GetHeaderByNumber retrieves a block header from the database by number,
  2442. // caching it (associated with its hash) if found.
  2443. func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  2444. return bc.hc.GetHeaderByNumber(number)
  2445. }
  2446. // GetTransactionLookup retrieves the lookup associate with the given transaction
  2447. // hash from the cache or database.
  2448. func (bc *BlockChain) GetTransactionLookup(hash common.Hash) *rawdb.LegacyTxLookupEntry {
  2449. // Short circuit if the txlookup already in the cache, retrieve otherwise
  2450. if lookup, exist := bc.txLookupCache.Get(hash); exist {
  2451. return lookup.(*rawdb.LegacyTxLookupEntry)
  2452. }
  2453. tx, blockHash, blockNumber, txIndex := rawdb.ReadTransaction(bc.db, hash)
  2454. if tx == nil {
  2455. return nil
  2456. }
  2457. lookup := &rawdb.LegacyTxLookupEntry{BlockHash: blockHash, BlockIndex: blockNumber, Index: txIndex}
  2458. bc.txLookupCache.Add(hash, lookup)
  2459. return lookup
  2460. }
  2461. // Config retrieves the chain's fork configuration.
  2462. func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig }
  2463. // QuorumConfig retrieves the Quorum chain's configuration
  2464. func (bc *BlockChain) QuorumConfig() *QuorumChainConfig { return bc.quorumConfig }
  2465. // Engine retrieves the blockchain's consensus engine.
  2466. func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  2467. // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  2468. func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  2469. return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  2470. }
  2471. // SubscribeChainEvent registers a subscription of ChainEvent.
  2472. func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  2473. return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  2474. }
  2475. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  2476. func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  2477. return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  2478. }
  2479. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  2480. func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  2481. return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  2482. }
  2483. // SubscribeLogsEvent registers a subscription of []*types.Log.
  2484. func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  2485. return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  2486. }
  2487. // SubscribeBlockProcessingEvent registers a subscription of bool where true means
  2488. // block processing has started while false means it has stopped.
  2489. func (bc *BlockChain) SubscribeBlockProcessingEvent(ch chan<- bool) event.Subscription {
  2490. return bc.scope.Track(bc.blockProcFeed.Subscribe(ch))
  2491. }
  2492. // Quorum
  2493. func (bc *BlockChain) SupportsMultitenancy(context.Context) bool {
  2494. return bc.quorumConfig.MultiTenantEnabled()
  2495. }
  2496. // PopulateSetPrivateState function pointer for updating private state
  2497. // Quorum
  2498. func (bc *BlockChain) PopulateSetPrivateState(ps func([]*types.Log, *state.StateDB, types.PrivateStateIdentifier)) {
  2499. bc.setPrivateState = ps
  2500. }
  2501. // CheckAndSetPrivateState function to update the private state as a part contract state extension
  2502. // Quorum
  2503. func (bc *BlockChain) CheckAndSetPrivateState(txLogs []*types.Log, privateState *state.StateDB, psi types.PrivateStateIdentifier) {
  2504. if bc.setPrivateState != nil {
  2505. bc.setPrivateState(txLogs, privateState, psi)
  2506. }
  2507. }