headerchain.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. "time"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/consensus"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/ethdb"
  29. "github.com/ethereum/go-ethereum/log"
  30. "github.com/ethereum/go-ethereum/params"
  31. "github.com/hashicorp/golang-lru"
  32. )
  33. const (
  34. headerCacheLimit = 512
  35. tdCacheLimit = 1024
  36. numberCacheLimit = 2048
  37. )
  38. // HeaderChain implements the basic block header chain logic that is shared by
  39. // core.BlockChain and light.LightChain. It is not usable in itself, only as
  40. // a part of either structure.
  41. // It is not thread safe either, the encapsulating chain structures should do
  42. // the necessary mutex locking/unlocking.
  43. type HeaderChain struct {
  44. config *params.ChainConfig
  45. chainDb ethdb.Database
  46. genesisHeader *types.Header
  47. currentHeader *types.Header // Current head of the header chain (may be above the block chain!)
  48. currentHeaderHash common.Hash // Hash of the current head of the header chain (prevent recomputing all the time)
  49. headerCache *lru.Cache // Cache for the most recent block headers
  50. tdCache *lru.Cache // Cache for the most recent block total difficulties
  51. numberCache *lru.Cache // Cache for the most recent block numbers
  52. procInterrupt func() bool
  53. rand *mrand.Rand
  54. engine consensus.Engine
  55. }
  56. // NewHeaderChain creates a new HeaderChain structure.
  57. // getValidator should return the parent's validator
  58. // procInterrupt points to the parent's interrupt semaphore
  59. // wg points to the parent's shutdown wait group
  60. func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) {
  61. headerCache, _ := lru.New(headerCacheLimit)
  62. tdCache, _ := lru.New(tdCacheLimit)
  63. numberCache, _ := lru.New(numberCacheLimit)
  64. // Seed a fast but crypto originating random generator
  65. seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
  66. if err != nil {
  67. return nil, err
  68. }
  69. hc := &HeaderChain{
  70. config: config,
  71. chainDb: chainDb,
  72. headerCache: headerCache,
  73. tdCache: tdCache,
  74. numberCache: numberCache,
  75. procInterrupt: procInterrupt,
  76. rand: mrand.New(mrand.NewSource(seed.Int64())),
  77. engine: engine,
  78. }
  79. hc.genesisHeader = hc.GetHeaderByNumber(0)
  80. if hc.genesisHeader == nil {
  81. return nil, ErrNoGenesis
  82. }
  83. hc.currentHeader = hc.genesisHeader
  84. if head := GetHeadBlockHash(chainDb); head != (common.Hash{}) {
  85. if chead := hc.GetHeaderByHash(head); chead != nil {
  86. hc.currentHeader = chead
  87. }
  88. }
  89. hc.currentHeaderHash = hc.currentHeader.Hash()
  90. return hc, nil
  91. }
  92. // GetBlockNumber retrieves the block number belonging to the given hash
  93. // from the cache or database
  94. func (hc *HeaderChain) GetBlockNumber(hash common.Hash) uint64 {
  95. if cached, ok := hc.numberCache.Get(hash); ok {
  96. return cached.(uint64)
  97. }
  98. number := GetBlockNumber(hc.chainDb, hash)
  99. if number != missingNumber {
  100. hc.numberCache.Add(hash, number)
  101. }
  102. return number
  103. }
  104. // WriteHeader writes a header into the local chain, given that its parent is
  105. // already known. If the total difficulty of the newly inserted header becomes
  106. // greater than the current known TD, the canonical chain is re-routed.
  107. //
  108. // Note: This method is not concurrent-safe with inserting blocks simultaneously
  109. // into the chain, as side effects caused by reorganisations cannot be emulated
  110. // without the real blocks. Hence, writing headers directly should only be done
  111. // in two scenarios: pure-header mode of operation (light clients), or properly
  112. // separated header/block phases (non-archive clients).
  113. func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, err error) {
  114. // Cache some values to prevent constant recalculation
  115. var (
  116. hash = header.Hash()
  117. number = header.Number.Uint64()
  118. )
  119. // Calculate the total difficulty of the header
  120. ptd := hc.GetTd(header.ParentHash, number-1)
  121. if ptd == nil {
  122. return NonStatTy, consensus.ErrUnknownAncestor
  123. }
  124. localTd := hc.GetTd(hc.currentHeaderHash, hc.currentHeader.Number.Uint64())
  125. externTd := new(big.Int).Add(header.Difficulty, ptd)
  126. // Irrelevant of the canonical status, write the td and header to the database
  127. if err := hc.WriteTd(hash, number, externTd); err != nil {
  128. log.Crit("Failed to write header total difficulty", "err", err)
  129. }
  130. if err := WriteHeader(hc.chainDb, header); err != nil {
  131. log.Crit("Failed to write header content", "err", err)
  132. }
  133. // If the total difficulty is higher than our known, add it to the canonical chain
  134. // Second clause in the if statement reduces the vulnerability to selfish mining.
  135. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  136. if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) {
  137. // Delete any canonical number assignments above the new head
  138. for i := number + 1; ; i++ {
  139. hash := GetCanonicalHash(hc.chainDb, i)
  140. if hash == (common.Hash{}) {
  141. break
  142. }
  143. DeleteCanonicalHash(hc.chainDb, i)
  144. }
  145. // Overwrite any stale canonical number assignments
  146. var (
  147. headHash = header.ParentHash
  148. headNumber = header.Number.Uint64() - 1
  149. headHeader = hc.GetHeader(headHash, headNumber)
  150. )
  151. for GetCanonicalHash(hc.chainDb, headNumber) != headHash {
  152. WriteCanonicalHash(hc.chainDb, headHash, headNumber)
  153. headHash = headHeader.ParentHash
  154. headNumber = headHeader.Number.Uint64() - 1
  155. headHeader = hc.GetHeader(headHash, headNumber)
  156. }
  157. // Extend the canonical chain with the new header
  158. if err := WriteCanonicalHash(hc.chainDb, hash, number); err != nil {
  159. log.Crit("Failed to insert header number", "err", err)
  160. }
  161. if err := WriteHeadHeaderHash(hc.chainDb, hash); err != nil {
  162. log.Crit("Failed to insert head header hash", "err", err)
  163. }
  164. hc.currentHeaderHash, hc.currentHeader = hash, 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 messge (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.GetHeader(header.Hash(), header.Number.Uint64()) != nil {
  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. // GetTd retrieves a block's total difficulty in the canonical chain from the
  277. // database by hash and number, caching it if found.
  278. func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int {
  279. // Short circuit if the td's already in the cache, retrieve otherwise
  280. if cached, ok := hc.tdCache.Get(hash); ok {
  281. return cached.(*big.Int)
  282. }
  283. td := GetTd(hc.chainDb, hash, number)
  284. if td == nil {
  285. return nil
  286. }
  287. // Cache the found body for next time and return
  288. hc.tdCache.Add(hash, td)
  289. return td
  290. }
  291. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  292. // database by hash, caching it if found.
  293. func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
  294. return hc.GetTd(hash, hc.GetBlockNumber(hash))
  295. }
  296. // WriteTd stores a block's total difficulty into the database, also caching it
  297. // along the way.
  298. func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) error {
  299. if err := WriteTd(hc.chainDb, hash, number, td); err != nil {
  300. return err
  301. }
  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 := GetHeader(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. return hc.GetHeader(hash, hc.GetBlockNumber(hash))
  324. }
  325. // HasHeader checks if a block header is present in the database or not, caching
  326. // it if present.
  327. func (hc *HeaderChain) HasHeader(hash common.Hash) bool {
  328. return hc.GetHeaderByHash(hash) != nil
  329. }
  330. // GetHeaderByNumber retrieves a block header from the database by number,
  331. // caching it (associated with its hash) if found.
  332. func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
  333. hash := GetCanonicalHash(hc.chainDb, number)
  334. if hash == (common.Hash{}) {
  335. return nil
  336. }
  337. return hc.GetHeader(hash, number)
  338. }
  339. // CurrentHeader retrieves the current head header of the canonical chain. The
  340. // header is retrieved from the HeaderChain's internal cache.
  341. func (hc *HeaderChain) CurrentHeader() *types.Header {
  342. return hc.currentHeader
  343. }
  344. // SetCurrentHeader sets the current head header of the canonical chain.
  345. func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
  346. if err := WriteHeadHeaderHash(hc.chainDb, head.Hash()); err != nil {
  347. log.Crit("Failed to insert head header hash", "err", err)
  348. }
  349. hc.currentHeader = head
  350. hc.currentHeaderHash = head.Hash()
  351. }
  352. // DeleteCallback is a callback function that is called by SetHead before
  353. // each header is deleted.
  354. type DeleteCallback func(common.Hash, uint64)
  355. // SetHead rewinds the local chain to a new head. Everything above the new head
  356. // will be deleted and the new one set.
  357. func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback) {
  358. height := uint64(0)
  359. if hc.currentHeader != nil {
  360. height = hc.currentHeader.Number.Uint64()
  361. }
  362. for hc.currentHeader != nil && hc.currentHeader.Number.Uint64() > head {
  363. hash := hc.currentHeader.Hash()
  364. num := hc.currentHeader.Number.Uint64()
  365. if delFn != nil {
  366. delFn(hash, num)
  367. }
  368. DeleteHeader(hc.chainDb, hash, num)
  369. DeleteTd(hc.chainDb, hash, num)
  370. hc.currentHeader = hc.GetHeader(hc.currentHeader.ParentHash, hc.currentHeader.Number.Uint64()-1)
  371. }
  372. // Roll back the canonical chain numbering
  373. for i := height; i > head; i-- {
  374. DeleteCanonicalHash(hc.chainDb, i)
  375. }
  376. // Clear out any stale content from the caches
  377. hc.headerCache.Purge()
  378. hc.tdCache.Purge()
  379. hc.numberCache.Purge()
  380. if hc.currentHeader == nil {
  381. hc.currentHeader = hc.genesisHeader
  382. }
  383. hc.currentHeaderHash = hc.currentHeader.Hash()
  384. if err := WriteHeadHeaderHash(hc.chainDb, hc.currentHeaderHash); err != nil {
  385. log.Crit("Failed to reset head header hash", "err", err)
  386. }
  387. }
  388. // SetGenesis sets a new genesis block header for the chain
  389. func (hc *HeaderChain) SetGenesis(head *types.Header) {
  390. hc.genesisHeader = head
  391. }
  392. // Config retrieves the header chain's chain configuration.
  393. func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config }
  394. // Engine retrieves the header chain's consensus engine.
  395. func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine }
  396. // GetBlock implements consensus.ChainReader, and returns nil for every input as
  397. // a header chain does not have blocks available for retrieval.
  398. func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  399. return nil
  400. }