headerchain.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. for i := number + 1; ; i++ {
  140. hash := rawdb.ReadCanonicalHash(hc.chainDb, i)
  141. if hash == (common.Hash{}) {
  142. break
  143. }
  144. rawdb.DeleteCanonicalHash(hc.chainDb, i)
  145. }
  146. // Overwrite any stale canonical number assignments
  147. var (
  148. headHash = header.ParentHash
  149. headNumber = header.Number.Uint64() - 1
  150. headHeader = hc.GetHeader(headHash, headNumber)
  151. )
  152. for rawdb.ReadCanonicalHash(hc.chainDb, headNumber) != headHash {
  153. rawdb.WriteCanonicalHash(hc.chainDb, headHash, headNumber)
  154. headHash = headHeader.ParentHash
  155. headNumber = headHeader.Number.Uint64() - 1
  156. headHeader = hc.GetHeader(headHash, headNumber)
  157. }
  158. // Extend the canonical chain with the new header
  159. rawdb.WriteCanonicalHash(hc.chainDb, hash, number)
  160. rawdb.WriteHeadHeaderHash(hc.chainDb, hash)
  161. hc.currentHeaderHash = hash
  162. hc.currentHeader.Store(types.CopyHeader(header))
  163. status = CanonStatTy
  164. } else {
  165. status = SideStatTy
  166. }
  167. hc.headerCache.Add(hash, header)
  168. hc.numberCache.Add(hash, number)
  169. return
  170. }
  171. // WhCallback is a callback function for inserting individual headers.
  172. // A callback is used for two reasons: first, in a LightChain, status should be
  173. // processed and light chain events sent, while in a BlockChain this is not
  174. // necessary since chain events are sent after inserting blocks. Second, the
  175. // header writes should be protected by the parent chain mutex individually.
  176. type WhCallback func(*types.Header) error
  177. func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  178. // Do a sanity check that the provided chain is actually ordered and linked
  179. for i := 1; i < len(chain); i++ {
  180. if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() {
  181. // Chain broke ancestry, log a messge (programming error) and skip insertion
  182. log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(),
  183. "parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash())
  184. 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,
  185. chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4])
  186. }
  187. }
  188. // Generate the list of seal verification requests, and start the parallel verifier
  189. seals := make([]bool, len(chain))
  190. for i := 0; i < len(seals)/checkFreq; i++ {
  191. index := i*checkFreq + hc.rand.Intn(checkFreq)
  192. if index >= len(seals) {
  193. index = len(seals) - 1
  194. }
  195. seals[index] = true
  196. }
  197. seals[len(seals)-1] = true // Last should always be verified to avoid junk
  198. abort, results := hc.engine.VerifyHeaders(hc, chain, seals)
  199. defer close(abort)
  200. // Iterate over the headers and ensure they all check out
  201. for i, header := range chain {
  202. // If the chain is terminating, stop processing blocks
  203. if hc.procInterrupt() {
  204. log.Debug("Premature abort during headers verification")
  205. return 0, errors.New("aborted")
  206. }
  207. // If the header is a banned one, straight out abort
  208. if BadHashes[header.Hash()] {
  209. return i, ErrBlacklistedHash
  210. }
  211. // Otherwise wait for headers checks and ensure they pass
  212. if err := <-results; err != nil {
  213. return i, err
  214. }
  215. }
  216. return 0, nil
  217. }
  218. // InsertHeaderChain attempts to insert the given header chain in to the local
  219. // chain, possibly creating a reorg. If an error is returned, it will return the
  220. // index number of the failing header as well an error describing what went wrong.
  221. //
  222. // The verify parameter can be used to fine tune whether nonce verification
  223. // should be done or not. The reason behind the optional check is because some
  224. // of the header retrieval mechanisms already need to verfy nonces, as well as
  225. // because nonces can be verified sparsely, not needing to check each.
  226. func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) {
  227. // Collect some import statistics to report on
  228. stats := struct{ processed, ignored int }{}
  229. // All headers passed verification, import them into the database
  230. for i, header := range chain {
  231. // Short circuit insertion if shutting down
  232. if hc.procInterrupt() {
  233. log.Debug("Premature abort during headers import")
  234. return i, errors.New("aborted")
  235. }
  236. // If the header's already known, skip it, otherwise store
  237. if hc.HasHeader(header.Hash(), header.Number.Uint64()) {
  238. stats.ignored++
  239. continue
  240. }
  241. if err := writeHeader(header); err != nil {
  242. return i, err
  243. }
  244. stats.processed++
  245. }
  246. // Report some public statistics so the user has a clue what's going on
  247. last := chain[len(chain)-1]
  248. log.Info("Imported new block headers", "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  249. "number", last.Number, "hash", last.Hash(), "ignored", stats.ignored)
  250. return 0, nil
  251. }
  252. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  253. // hash, fetching towards the genesis block.
  254. func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  255. // Get the origin header from which to fetch
  256. header := hc.GetHeaderByHash(hash)
  257. if header == nil {
  258. return nil
  259. }
  260. // Iterate the headers until enough is collected or the genesis reached
  261. chain := make([]common.Hash, 0, max)
  262. for i := uint64(0); i < max; i++ {
  263. next := header.ParentHash
  264. if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil {
  265. break
  266. }
  267. chain = append(chain, next)
  268. if header.Number.Sign() == 0 {
  269. break
  270. }
  271. }
  272. return chain
  273. }
  274. // GetTd retrieves a block's total difficulty in the canonical chain from the
  275. // database by hash and number, caching it if found.
  276. func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int {
  277. // Short circuit if the td's already in the cache, retrieve otherwise
  278. if cached, ok := hc.tdCache.Get(hash); ok {
  279. return cached.(*big.Int)
  280. }
  281. td := rawdb.ReadTd(hc.chainDb, hash, number)
  282. if td == nil {
  283. return nil
  284. }
  285. // Cache the found body for next time and return
  286. hc.tdCache.Add(hash, td)
  287. return td
  288. }
  289. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  290. // database by hash, caching it if found.
  291. func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
  292. number := hc.GetBlockNumber(hash)
  293. if number == nil {
  294. return nil
  295. }
  296. return hc.GetTd(hash, *number)
  297. }
  298. // WriteTd stores a block's total difficulty into the database, also caching it
  299. // along the way.
  300. func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) error {
  301. rawdb.WriteTd(hc.chainDb, hash, number, td)
  302. hc.tdCache.Add(hash, new(big.Int).Set(td))
  303. return nil
  304. }
  305. // GetHeader retrieves a block header from the database by hash and number,
  306. // caching it if found.
  307. func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  308. // Short circuit if the header's already in the cache, retrieve otherwise
  309. if header, ok := hc.headerCache.Get(hash); ok {
  310. return header.(*types.Header)
  311. }
  312. header := rawdb.ReadHeader(hc.chainDb, hash, number)
  313. if header == nil {
  314. return nil
  315. }
  316. // Cache the found header for next time and return
  317. hc.headerCache.Add(hash, header)
  318. return header
  319. }
  320. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  321. // found.
  322. func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header {
  323. number := hc.GetBlockNumber(hash)
  324. if number == nil {
  325. return nil
  326. }
  327. return hc.GetHeader(hash, *number)
  328. }
  329. // HasHeader checks if a block header is present in the database or not.
  330. func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
  331. if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) {
  332. return true
  333. }
  334. return rawdb.HasHeader(hc.chainDb, hash, number)
  335. }
  336. // GetHeaderByNumber retrieves a block header from the database by number,
  337. // caching it (associated with its hash) if found.
  338. func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
  339. hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
  340. if hash == (common.Hash{}) {
  341. return nil
  342. }
  343. return hc.GetHeader(hash, number)
  344. }
  345. // CurrentHeader retrieves the current head header of the canonical chain. The
  346. // header is retrieved from the HeaderChain's internal cache.
  347. func (hc *HeaderChain) CurrentHeader() *types.Header {
  348. return hc.currentHeader.Load().(*types.Header)
  349. }
  350. // SetCurrentHeader sets the current head header of the canonical chain.
  351. func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
  352. rawdb.WriteHeadHeaderHash(hc.chainDb, head.Hash())
  353. hc.currentHeader.Store(head)
  354. hc.currentHeaderHash = head.Hash()
  355. }
  356. // DeleteCallback is a callback function that is called by SetHead before
  357. // each header is deleted.
  358. type DeleteCallback func(common.Hash, uint64)
  359. // SetHead rewinds the local chain to a new head. Everything above the new head
  360. // will be deleted and the new one set.
  361. func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback) {
  362. height := uint64(0)
  363. if hdr := hc.CurrentHeader(); hdr != nil {
  364. height = hdr.Number.Uint64()
  365. }
  366. for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() {
  367. hash := hdr.Hash()
  368. num := hdr.Number.Uint64()
  369. if delFn != nil {
  370. delFn(hash, num)
  371. }
  372. rawdb.DeleteHeader(hc.chainDb, hash, num)
  373. rawdb.DeleteTd(hc.chainDb, hash, num)
  374. hc.currentHeader.Store(hc.GetHeader(hdr.ParentHash, hdr.Number.Uint64()-1))
  375. }
  376. // Roll back the canonical chain numbering
  377. for i := height; i > head; i-- {
  378. rawdb.DeleteCanonicalHash(hc.chainDb, i)
  379. }
  380. // Clear out any stale content from the caches
  381. hc.headerCache.Purge()
  382. hc.tdCache.Purge()
  383. hc.numberCache.Purge()
  384. if hc.CurrentHeader() == nil {
  385. hc.currentHeader.Store(hc.genesisHeader)
  386. }
  387. hc.currentHeaderHash = hc.CurrentHeader().Hash()
  388. rawdb.WriteHeadHeaderHash(hc.chainDb, hc.currentHeaderHash)
  389. }
  390. // SetGenesis sets a new genesis block header for the chain
  391. func (hc *HeaderChain) SetGenesis(head *types.Header) {
  392. hc.genesisHeader = head
  393. }
  394. // Config retrieves the header chain's chain configuration.
  395. func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config }
  396. // Engine retrieves the header chain's consensus engine.
  397. func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine }
  398. // GetBlock implements consensus.ChainReader, and returns nil for every input as
  399. // a header chain does not have blocks available for retrieval.
  400. func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  401. return nil
  402. }