headerchain.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package core
  17. import (
  18. crand "crypto/rand"
  19. "errors"
  20. "fmt"
  21. "math"
  22. "math/big"
  23. mrand "math/rand"
  24. "sync/atomic"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/consensus"
  28. "github.com/ethereum/go-ethereum/core/rawdb"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/log"
  32. "github.com/ethereum/go-ethereum/params"
  33. lru "github.com/hashicorp/golang-lru"
  34. )
  35. const (
  36. headerCacheLimit = 512
  37. tdCacheLimit = 1024
  38. numberCacheLimit = 2048
  39. )
  40. // HeaderChain implements the basic block header chain logic that is shared by
  41. // core.BlockChain and light.LightChain. It is not usable in itself, only as
  42. // a part of either structure.
  43. // It is not thread safe either, the encapsulating chain structures should do
  44. // the necessary mutex locking/unlocking.
  45. type HeaderChain struct {
  46. config *params.ChainConfig
  47. chainDb ethdb.Database
  48. genesisHeader *types.Header
  49. currentHeader atomic.Value // Current head of the header chain (may be above the block chain!)
  50. currentHeaderHash common.Hash // Hash of the current head of the header chain (prevent recomputing all the time)
  51. headerCache *lru.Cache // Cache for the most recent block headers
  52. tdCache *lru.Cache // Cache for the most recent block total difficulties
  53. numberCache *lru.Cache // Cache for the most recent block numbers
  54. procInterrupt func() bool
  55. rand *mrand.Rand
  56. engine consensus.Engine
  57. }
  58. // NewHeaderChain creates a new HeaderChain structure.
  59. // getValidator should return the parent's validator
  60. // procInterrupt points to the parent's interrupt semaphore
  61. // wg points to the parent's shutdown wait group
  62. func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) {
  63. headerCache, _ := lru.New(headerCacheLimit)
  64. tdCache, _ := lru.New(tdCacheLimit)
  65. numberCache, _ := lru.New(numberCacheLimit)
  66. // Seed a fast but crypto originating random generator
  67. seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
  68. if err != nil {
  69. return nil, err
  70. }
  71. hc := &HeaderChain{
  72. config: config,
  73. chainDb: chainDb,
  74. headerCache: headerCache,
  75. tdCache: tdCache,
  76. numberCache: numberCache,
  77. procInterrupt: procInterrupt,
  78. rand: mrand.New(mrand.NewSource(seed.Int64())),
  79. engine: engine,
  80. }
  81. hc.genesisHeader = hc.GetHeaderByNumber(0)
  82. if hc.genesisHeader == nil {
  83. return nil, ErrNoGenesis
  84. }
  85. hc.currentHeader.Store(hc.genesisHeader)
  86. if head := rawdb.ReadHeadBlockHash(chainDb); head != (common.Hash{}) {
  87. if chead := hc.GetHeaderByHash(head); chead != nil {
  88. hc.currentHeader.Store(chead)
  89. }
  90. }
  91. hc.currentHeaderHash = hc.CurrentHeader().Hash()
  92. return hc, nil
  93. }
  94. // GetBlockNumber retrieves the block number belonging to the given hash
  95. // from the cache or database
  96. func (hc *HeaderChain) GetBlockNumber(hash common.Hash) *uint64 {
  97. if cached, ok := hc.numberCache.Get(hash); ok {
  98. number := cached.(uint64)
  99. return &number
  100. }
  101. number := rawdb.ReadHeaderNumber(hc.chainDb, hash)
  102. if number != nil {
  103. hc.numberCache.Add(hash, *number)
  104. }
  105. return number
  106. }
  107. // WriteHeader writes a header into the local chain, given that its parent is
  108. // already known. If the total difficulty of the newly inserted header becomes
  109. // greater than the current known TD, the canonical chain is re-routed.
  110. //
  111. // Note: This method is not concurrent-safe with inserting blocks simultaneously
  112. // into the chain, as side effects caused by reorganisations cannot be emulated
  113. // without the real blocks. Hence, writing headers directly should only be done
  114. // in two scenarios: pure-header mode of operation (light clients), or properly
  115. // separated header/block phases (non-archive clients).
  116. func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, err error) {
  117. // Cache some values to prevent constant recalculation
  118. var (
  119. hash = header.Hash()
  120. number = header.Number.Uint64()
  121. )
  122. // Calculate the total difficulty of the header
  123. ptd := hc.GetTd(header.ParentHash, number-1)
  124. if ptd == nil {
  125. return NonStatTy, consensus.ErrUnknownAncestor
  126. }
  127. localTd := hc.GetTd(hc.currentHeaderHash, hc.CurrentHeader().Number.Uint64())
  128. externTd := new(big.Int).Add(header.Difficulty, ptd)
  129. // Irrelevant of the canonical status, write the td and header to the database
  130. if err := hc.WriteTd(hash, number, externTd); err != nil {
  131. log.Crit("Failed to write header total difficulty", "err", err)
  132. }
  133. rawdb.WriteHeader(hc.chainDb, header)
  134. // If the total difficulty is higher than our known, add it to the canonical chain
  135. // Second clause in the if statement reduces the vulnerability to selfish mining.
  136. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  137. if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) {
  138. // Delete any canonical number assignments above the new head
  139. batch := hc.chainDb.NewBatch()
  140. for i := number + 1; ; i++ {
  141. hash := rawdb.ReadCanonicalHash(hc.chainDb, i)
  142. if hash == (common.Hash{}) {
  143. break
  144. }
  145. rawdb.DeleteCanonicalHash(batch, i)
  146. }
  147. batch.Write()
  148. // Overwrite any stale canonical number assignments
  149. var (
  150. headHash = header.ParentHash
  151. headNumber = header.Number.Uint64() - 1
  152. headHeader = hc.GetHeader(headHash, headNumber)
  153. )
  154. for rawdb.ReadCanonicalHash(hc.chainDb, headNumber) != headHash {
  155. rawdb.WriteCanonicalHash(hc.chainDb, headHash, headNumber)
  156. headHash = headHeader.ParentHash
  157. headNumber = headHeader.Number.Uint64() - 1
  158. headHeader = hc.GetHeader(headHash, headNumber)
  159. }
  160. // Extend the canonical chain with the new header
  161. rawdb.WriteCanonicalHash(hc.chainDb, hash, number)
  162. rawdb.WriteHeadHeaderHash(hc.chainDb, hash)
  163. hc.currentHeaderHash = hash
  164. hc.currentHeader.Store(types.CopyHeader(header))
  165. status = CanonStatTy
  166. } else {
  167. status = SideStatTy
  168. }
  169. hc.headerCache.Add(hash, header)
  170. hc.numberCache.Add(hash, number)
  171. return
  172. }
  173. // WhCallback is a callback function for inserting individual headers.
  174. // A callback is used for two reasons: first, in a LightChain, status should be
  175. // processed and light chain events sent, while in a BlockChain this is not
  176. // necessary since chain events are sent after inserting blocks. Second, the
  177. // header writes should be protected by the parent chain mutex individually.
  178. type WhCallback func(*types.Header) error
  179. func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  180. // Do a sanity check that the provided chain is actually ordered and linked
  181. for i := 1; i < len(chain); i++ {
  182. if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() {
  183. // Chain broke ancestry, log a message (programming error) and skip insertion
  184. log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(),
  185. "parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash())
  186. return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].Number,
  187. chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4])
  188. }
  189. }
  190. // Generate the list of seal verification requests, and start the parallel verifier
  191. seals := make([]bool, len(chain))
  192. if checkFreq != 0 {
  193. // In case of checkFreq == 0 all seals are left false.
  194. for i := 0; i < len(seals)/checkFreq; i++ {
  195. index := i*checkFreq + hc.rand.Intn(checkFreq)
  196. if index >= len(seals) {
  197. index = len(seals) - 1
  198. }
  199. seals[index] = true
  200. }
  201. // Last should always be verified to avoid junk.
  202. seals[len(seals)-1] = true
  203. }
  204. abort, results := hc.engine.VerifyHeaders(hc, chain, seals)
  205. defer close(abort)
  206. // Iterate over the headers and ensure they all check out
  207. for i, header := range chain {
  208. // If the chain is terminating, stop processing blocks
  209. if hc.procInterrupt() {
  210. log.Debug("Premature abort during headers verification")
  211. return 0, errors.New("aborted")
  212. }
  213. // If the header is a banned one, straight out abort
  214. if BadHashes[header.Hash()] {
  215. return i, ErrBlacklistedHash
  216. }
  217. // Otherwise wait for headers checks and ensure they pass
  218. if err := <-results; err != nil {
  219. return i, err
  220. }
  221. }
  222. return 0, nil
  223. }
  224. // InsertHeaderChain attempts to insert the given header chain in to the local
  225. // chain, possibly creating a reorg. If an error is returned, it will return the
  226. // index number of the failing header as well an error describing what went wrong.
  227. //
  228. // The verify parameter can be used to fine tune whether nonce verification
  229. // should be done or not. The reason behind the optional check is because some
  230. // of the header retrieval mechanisms already need to verfy nonces, as well as
  231. // because nonces can be verified sparsely, not needing to check each.
  232. func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) {
  233. // Collect some import statistics to report on
  234. stats := struct{ processed, ignored int }{}
  235. // All headers passed verification, import them into the database
  236. for i, header := range chain {
  237. // Short circuit insertion if shutting down
  238. if hc.procInterrupt() {
  239. log.Debug("Premature abort during headers import")
  240. return i, errors.New("aborted")
  241. }
  242. // If the header's already known, skip it, otherwise store
  243. if hc.HasHeader(header.Hash(), header.Number.Uint64()) {
  244. stats.ignored++
  245. continue
  246. }
  247. if err := writeHeader(header); err != nil {
  248. return i, err
  249. }
  250. stats.processed++
  251. }
  252. // Report some public statistics so the user has a clue what's going on
  253. last := chain[len(chain)-1]
  254. context := []interface{}{
  255. "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  256. "number", last.Number, "hash", last.Hash(),
  257. }
  258. if timestamp := time.Unix(int64(last.Time), 0); time.Since(timestamp) > time.Minute {
  259. context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...)
  260. }
  261. if stats.ignored > 0 {
  262. context = append(context, []interface{}{"ignored", stats.ignored}...)
  263. }
  264. log.Info("Imported new block headers", context...)
  265. return 0, nil
  266. }
  267. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  268. // hash, fetching towards the genesis block.
  269. func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  270. // Get the origin header from which to fetch
  271. header := hc.GetHeaderByHash(hash)
  272. if header == nil {
  273. return nil
  274. }
  275. // Iterate the headers until enough is collected or the genesis reached
  276. chain := make([]common.Hash, 0, max)
  277. for i := uint64(0); i < max; i++ {
  278. next := header.ParentHash
  279. if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil {
  280. break
  281. }
  282. chain = append(chain, next)
  283. if header.Number.Sign() == 0 {
  284. break
  285. }
  286. }
  287. return chain
  288. }
  289. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  290. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  291. // number of blocks to be individually checked before we reach the canonical chain.
  292. //
  293. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  294. func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  295. if ancestor > number {
  296. return common.Hash{}, 0
  297. }
  298. if ancestor == 1 {
  299. // in this case it is cheaper to just read the header
  300. if header := hc.GetHeader(hash, number); header != nil {
  301. return header.ParentHash, number - 1
  302. } else {
  303. return common.Hash{}, 0
  304. }
  305. }
  306. for ancestor != 0 {
  307. if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash {
  308. number -= ancestor
  309. return rawdb.ReadCanonicalHash(hc.chainDb, number), number
  310. }
  311. if *maxNonCanonical == 0 {
  312. return common.Hash{}, 0
  313. }
  314. *maxNonCanonical--
  315. ancestor--
  316. header := hc.GetHeader(hash, number)
  317. if header == nil {
  318. return common.Hash{}, 0
  319. }
  320. hash = header.ParentHash
  321. number--
  322. }
  323. return hash, number
  324. }
  325. // GetTd retrieves a block's total difficulty in the canonical chain from the
  326. // database by hash and number, caching it if found.
  327. func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int {
  328. // Short circuit if the td's already in the cache, retrieve otherwise
  329. if cached, ok := hc.tdCache.Get(hash); ok {
  330. return cached.(*big.Int)
  331. }
  332. td := rawdb.ReadTd(hc.chainDb, hash, number)
  333. if td == nil {
  334. return nil
  335. }
  336. // Cache the found body for next time and return
  337. hc.tdCache.Add(hash, td)
  338. return td
  339. }
  340. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  341. // database by hash, caching it if found.
  342. func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
  343. number := hc.GetBlockNumber(hash)
  344. if number == nil {
  345. return nil
  346. }
  347. return hc.GetTd(hash, *number)
  348. }
  349. // WriteTd stores a block's total difficulty into the database, also caching it
  350. // along the way.
  351. func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) error {
  352. rawdb.WriteTd(hc.chainDb, hash, number, td)
  353. hc.tdCache.Add(hash, new(big.Int).Set(td))
  354. return nil
  355. }
  356. // GetHeader retrieves a block header from the database by hash and number,
  357. // caching it if found.
  358. func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  359. // Short circuit if the header's already in the cache, retrieve otherwise
  360. if header, ok := hc.headerCache.Get(hash); ok {
  361. return header.(*types.Header)
  362. }
  363. header := rawdb.ReadHeader(hc.chainDb, hash, number)
  364. if header == nil {
  365. return nil
  366. }
  367. // Cache the found header for next time and return
  368. hc.headerCache.Add(hash, header)
  369. return header
  370. }
  371. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  372. // found.
  373. func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header {
  374. number := hc.GetBlockNumber(hash)
  375. if number == nil {
  376. return nil
  377. }
  378. return hc.GetHeader(hash, *number)
  379. }
  380. // HasHeader checks if a block header is present in the database or not.
  381. func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
  382. if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) {
  383. return true
  384. }
  385. return rawdb.HasHeader(hc.chainDb, hash, number)
  386. }
  387. // GetHeaderByNumber retrieves a block header from the database by number,
  388. // caching it (associated with its hash) if found.
  389. func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
  390. hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
  391. if hash == (common.Hash{}) {
  392. return nil
  393. }
  394. return hc.GetHeader(hash, number)
  395. }
  396. // CurrentHeader retrieves the current head header of the canonical chain. The
  397. // header is retrieved from the HeaderChain's internal cache.
  398. func (hc *HeaderChain) CurrentHeader() *types.Header {
  399. return hc.currentHeader.Load().(*types.Header)
  400. }
  401. // SetCurrentHeader sets the current head header of the canonical chain.
  402. func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
  403. rawdb.WriteHeadHeaderHash(hc.chainDb, head.Hash())
  404. hc.currentHeader.Store(head)
  405. hc.currentHeaderHash = head.Hash()
  406. }
  407. type (
  408. // UpdateHeadBlocksCallback is a callback function that is called by SetHead
  409. // before head header is updated.
  410. UpdateHeadBlocksCallback func(ethdb.KeyValueWriter, *types.Header)
  411. // DeleteBlockContentCallback is a callback function that is called by SetHead
  412. // before each header is deleted.
  413. DeleteBlockContentCallback func(ethdb.KeyValueWriter, common.Hash, uint64)
  414. )
  415. // SetHead rewinds the local chain to a new head. Everything above the new head
  416. // will be deleted and the new one set.
  417. func (hc *HeaderChain) SetHead(head uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) {
  418. var (
  419. parentHash common.Hash
  420. batch = hc.chainDb.NewBatch()
  421. )
  422. for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() {
  423. hash, num := hdr.Hash(), hdr.Number.Uint64()
  424. // Rewind block chain to new head.
  425. parent := hc.GetHeader(hdr.ParentHash, num-1)
  426. if parent == nil {
  427. parent = hc.genesisHeader
  428. }
  429. parentHash = hdr.ParentHash
  430. // Notably, since geth has the possibility for setting the head to a low
  431. // height which is even lower than ancient head.
  432. // In order to ensure that the head is always no higher than the data in
  433. // the database(ancient store or active store), we need to update head
  434. // first then remove the relative data from the database.
  435. //
  436. // Update head first(head fast block, head full block) before deleting the data.
  437. if updateFn != nil {
  438. updateFn(hc.chainDb, parent)
  439. }
  440. // Update head header then.
  441. rawdb.WriteHeadHeaderHash(hc.chainDb, parentHash)
  442. // Remove the relative data from the database.
  443. if delFn != nil {
  444. delFn(batch, hash, num)
  445. }
  446. // Rewind header chain to new head.
  447. rawdb.DeleteHeader(batch, hash, num)
  448. rawdb.DeleteTd(batch, hash, num)
  449. rawdb.DeleteCanonicalHash(batch, num)
  450. hc.currentHeader.Store(parent)
  451. hc.currentHeaderHash = parentHash
  452. }
  453. batch.Write()
  454. // Clear out any stale content from the caches
  455. hc.headerCache.Purge()
  456. hc.tdCache.Purge()
  457. hc.numberCache.Purge()
  458. }
  459. // SetGenesis sets a new genesis block header for the chain
  460. func (hc *HeaderChain) SetGenesis(head *types.Header) {
  461. hc.genesisHeader = head
  462. }
  463. // Config retrieves the header chain's chain configuration.
  464. func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config }
  465. // Engine retrieves the header chain's consensus engine.
  466. func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine }
  467. // GetBlock implements consensus.ChainReader, and returns nil for every input as
  468. // a header chain does not have blocks available for retrieval.
  469. func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  470. return nil
  471. }