headerchain.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. "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. for i := 0; i < len(seals)/checkFreq; i++ {
  193. index := i*checkFreq + hc.rand.Intn(checkFreq)
  194. if index >= len(seals) {
  195. index = len(seals) - 1
  196. }
  197. seals[index] = true
  198. }
  199. seals[len(seals)-1] = true // Last should always be verified to avoid junk
  200. abort, results := hc.engine.VerifyHeaders(hc, chain, seals)
  201. defer close(abort)
  202. // Iterate over the headers and ensure they all check out
  203. for i, header := range chain {
  204. // If the chain is terminating, stop processing blocks
  205. if hc.procInterrupt() {
  206. log.Debug("Premature abort during headers verification")
  207. return 0, errors.New("aborted")
  208. }
  209. // If the header is a banned one, straight out abort
  210. if BadHashes[header.Hash()] {
  211. return i, ErrBlacklistedHash
  212. }
  213. // Otherwise wait for headers checks and ensure they pass
  214. if err := <-results; err != nil {
  215. return i, err
  216. }
  217. }
  218. return 0, nil
  219. }
  220. // InsertHeaderChain attempts to insert the given header chain in to the local
  221. // chain, possibly creating a reorg. If an error is returned, it will return the
  222. // index number of the failing header as well an error describing what went wrong.
  223. //
  224. // The verify parameter can be used to fine tune whether nonce verification
  225. // should be done or not. The reason behind the optional check is because some
  226. // of the header retrieval mechanisms already need to verfy nonces, as well as
  227. // because nonces can be verified sparsely, not needing to check each.
  228. func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) {
  229. // Collect some import statistics to report on
  230. stats := struct{ processed, ignored int }{}
  231. // All headers passed verification, import them into the database
  232. for i, header := range chain {
  233. // Short circuit insertion if shutting down
  234. if hc.procInterrupt() {
  235. log.Debug("Premature abort during headers import")
  236. return i, errors.New("aborted")
  237. }
  238. // If the header's already known, skip it, otherwise store
  239. if hc.HasHeader(header.Hash(), header.Number.Uint64()) {
  240. stats.ignored++
  241. continue
  242. }
  243. if err := writeHeader(header); err != nil {
  244. return i, err
  245. }
  246. stats.processed++
  247. }
  248. // Report some public statistics so the user has a clue what's going on
  249. last := chain[len(chain)-1]
  250. log.Info("Imported new block headers", "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  251. "number", last.Number, "hash", last.Hash(), "ignored", stats.ignored)
  252. return 0, nil
  253. }
  254. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  255. // hash, fetching towards the genesis block.
  256. func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  257. // Get the origin header from which to fetch
  258. header := hc.GetHeaderByHash(hash)
  259. if header == nil {
  260. return nil
  261. }
  262. // Iterate the headers until enough is collected or the genesis reached
  263. chain := make([]common.Hash, 0, max)
  264. for i := uint64(0); i < max; i++ {
  265. next := header.ParentHash
  266. if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil {
  267. break
  268. }
  269. chain = append(chain, next)
  270. if header.Number.Sign() == 0 {
  271. break
  272. }
  273. }
  274. return chain
  275. }
  276. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  277. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  278. // number of blocks to be individually checked before we reach the canonical chain.
  279. //
  280. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  281. func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  282. if ancestor > number {
  283. return common.Hash{}, 0
  284. }
  285. if ancestor == 1 {
  286. // in this case it is cheaper to just read the header
  287. if header := hc.GetHeader(hash, number); header != nil {
  288. return header.ParentHash, number - 1
  289. } else {
  290. return common.Hash{}, 0
  291. }
  292. }
  293. for ancestor != 0 {
  294. if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash {
  295. number -= ancestor
  296. return rawdb.ReadCanonicalHash(hc.chainDb, number), number
  297. }
  298. if *maxNonCanonical == 0 {
  299. return common.Hash{}, 0
  300. }
  301. *maxNonCanonical--
  302. ancestor--
  303. header := hc.GetHeader(hash, number)
  304. if header == nil {
  305. return common.Hash{}, 0
  306. }
  307. hash = header.ParentHash
  308. number--
  309. }
  310. return hash, number
  311. }
  312. // GetTd retrieves a block's total difficulty in the canonical chain from the
  313. // database by hash and number, caching it if found.
  314. func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int {
  315. // Short circuit if the td's already in the cache, retrieve otherwise
  316. if cached, ok := hc.tdCache.Get(hash); ok {
  317. return cached.(*big.Int)
  318. }
  319. td := rawdb.ReadTd(hc.chainDb, hash, number)
  320. if td == nil {
  321. return nil
  322. }
  323. // Cache the found body for next time and return
  324. hc.tdCache.Add(hash, td)
  325. return td
  326. }
  327. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  328. // database by hash, caching it if found.
  329. func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
  330. number := hc.GetBlockNumber(hash)
  331. if number == nil {
  332. return nil
  333. }
  334. return hc.GetTd(hash, *number)
  335. }
  336. // WriteTd stores a block's total difficulty into the database, also caching it
  337. // along the way.
  338. func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) error {
  339. rawdb.WriteTd(hc.chainDb, hash, number, td)
  340. hc.tdCache.Add(hash, new(big.Int).Set(td))
  341. return nil
  342. }
  343. // GetHeader retrieves a block header from the database by hash and number,
  344. // caching it if found.
  345. func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  346. // Short circuit if the header's already in the cache, retrieve otherwise
  347. if header, ok := hc.headerCache.Get(hash); ok {
  348. return header.(*types.Header)
  349. }
  350. header := rawdb.ReadHeader(hc.chainDb, hash, number)
  351. if header == nil {
  352. return nil
  353. }
  354. // Cache the found header for next time and return
  355. hc.headerCache.Add(hash, header)
  356. return header
  357. }
  358. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  359. // found.
  360. func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header {
  361. number := hc.GetBlockNumber(hash)
  362. if number == nil {
  363. return nil
  364. }
  365. return hc.GetHeader(hash, *number)
  366. }
  367. // HasHeader checks if a block header is present in the database or not.
  368. func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
  369. if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) {
  370. return true
  371. }
  372. return rawdb.HasHeader(hc.chainDb, hash, number)
  373. }
  374. // GetHeaderByNumber retrieves a block header from the database by number,
  375. // caching it (associated with its hash) if found.
  376. func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
  377. hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
  378. if hash == (common.Hash{}) {
  379. return nil
  380. }
  381. return hc.GetHeader(hash, number)
  382. }
  383. // CurrentHeader retrieves the current head header of the canonical chain. The
  384. // header is retrieved from the HeaderChain's internal cache.
  385. func (hc *HeaderChain) CurrentHeader() *types.Header {
  386. return hc.currentHeader.Load().(*types.Header)
  387. }
  388. // SetCurrentHeader sets the current head header of the canonical chain.
  389. func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
  390. rawdb.WriteHeadHeaderHash(hc.chainDb, head.Hash())
  391. hc.currentHeader.Store(head)
  392. hc.currentHeaderHash = head.Hash()
  393. }
  394. // DeleteCallback is a callback function that is called by SetHead before
  395. // each header is deleted.
  396. type DeleteCallback func(rawdb.DatabaseDeleter, common.Hash, uint64)
  397. // SetHead rewinds the local chain to a new head. Everything above the new head
  398. // will be deleted and the new one set.
  399. func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback) {
  400. height := uint64(0)
  401. if hdr := hc.CurrentHeader(); hdr != nil {
  402. height = hdr.Number.Uint64()
  403. }
  404. batch := hc.chainDb.NewBatch()
  405. for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() {
  406. hash := hdr.Hash()
  407. num := hdr.Number.Uint64()
  408. if delFn != nil {
  409. delFn(batch, hash, num)
  410. }
  411. rawdb.DeleteHeader(batch, hash, num)
  412. rawdb.DeleteTd(batch, hash, num)
  413. hc.currentHeader.Store(hc.GetHeader(hdr.ParentHash, hdr.Number.Uint64()-1))
  414. }
  415. // Roll back the canonical chain numbering
  416. for i := height; i > head; i-- {
  417. rawdb.DeleteCanonicalHash(batch, i)
  418. }
  419. batch.Write()
  420. // Clear out any stale content from the caches
  421. hc.headerCache.Purge()
  422. hc.tdCache.Purge()
  423. hc.numberCache.Purge()
  424. if hc.CurrentHeader() == nil {
  425. hc.currentHeader.Store(hc.genesisHeader)
  426. }
  427. hc.currentHeaderHash = hc.CurrentHeader().Hash()
  428. rawdb.WriteHeadHeaderHash(hc.chainDb, hc.currentHeaderHash)
  429. }
  430. // SetGenesis sets a new genesis block header for the chain
  431. func (hc *HeaderChain) SetGenesis(head *types.Header) {
  432. hc.genesisHeader = head
  433. }
  434. // Config retrieves the header chain's chain configuration.
  435. func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config }
  436. // Engine retrieves the header chain's consensus engine.
  437. func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine }
  438. // GetBlock implements consensus.ChainReader, and returns nil for every input as
  439. // a header chain does not have blocks available for retrieval.
  440. func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  441. return nil
  442. }