headerchain.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. "sync/atomic"
  33. )
  34. const (
  35. headerCacheLimit = 512
  36. tdCacheLimit = 1024
  37. numberCacheLimit = 2048
  38. )
  39. // HeaderChain implements the basic block header chain logic that is shared by
  40. // core.BlockChain and light.LightChain. It is not usable in itself, only as
  41. // a part of either structure.
  42. // It is not thread safe either, the encapsulating chain structures should do
  43. // the necessary mutex locking/unlocking.
  44. type HeaderChain struct {
  45. config *params.ChainConfig
  46. chainDb ethdb.Database
  47. genesisHeader *types.Header
  48. currentHeader atomic.Value // Current head of the header chain (may be above the block chain!)
  49. currentHeaderHash common.Hash // Hash of the current head of the header chain (prevent recomputing all the time)
  50. headerCache *lru.Cache // Cache for the most recent block headers
  51. tdCache *lru.Cache // Cache for the most recent block total difficulties
  52. numberCache *lru.Cache // Cache for the most recent block numbers
  53. procInterrupt func() bool
  54. rand *mrand.Rand
  55. engine consensus.Engine
  56. }
  57. // NewHeaderChain creates a new HeaderChain structure.
  58. // getValidator should return the parent's validator
  59. // procInterrupt points to the parent's interrupt semaphore
  60. // wg points to the parent's shutdown wait group
  61. func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) {
  62. headerCache, _ := lru.New(headerCacheLimit)
  63. tdCache, _ := lru.New(tdCacheLimit)
  64. numberCache, _ := lru.New(numberCacheLimit)
  65. // Seed a fast but crypto originating random generator
  66. seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
  67. if err != nil {
  68. return nil, err
  69. }
  70. hc := &HeaderChain{
  71. config: config,
  72. chainDb: chainDb,
  73. headerCache: headerCache,
  74. tdCache: tdCache,
  75. numberCache: numberCache,
  76. procInterrupt: procInterrupt,
  77. rand: mrand.New(mrand.NewSource(seed.Int64())),
  78. engine: engine,
  79. }
  80. hc.genesisHeader = hc.GetHeaderByNumber(0)
  81. if hc.genesisHeader == nil {
  82. return nil, ErrNoGenesis
  83. }
  84. hc.currentHeader.Store(hc.genesisHeader)
  85. if head := GetHeadBlockHash(chainDb); head != (common.Hash{}) {
  86. if chead := hc.GetHeaderByHash(head); chead != nil {
  87. hc.currentHeader.Store(chead)
  88. }
  89. }
  90. hc.currentHeaderHash = hc.CurrentHeader().Hash()
  91. return hc, nil
  92. }
  93. // GetBlockNumber retrieves the block number belonging to the given hash
  94. // from the cache or database
  95. func (hc *HeaderChain) GetBlockNumber(hash common.Hash) uint64 {
  96. if cached, ok := hc.numberCache.Get(hash); ok {
  97. return cached.(uint64)
  98. }
  99. number := GetBlockNumber(hc.chainDb, hash)
  100. if number != missingNumber {
  101. hc.numberCache.Add(hash, number)
  102. }
  103. return number
  104. }
  105. // WriteHeader writes a header into the local chain, given that its parent is
  106. // already known. If the total difficulty of the newly inserted header becomes
  107. // greater than the current known TD, the canonical chain is re-routed.
  108. //
  109. // Note: This method is not concurrent-safe with inserting blocks simultaneously
  110. // into the chain, as side effects caused by reorganisations cannot be emulated
  111. // without the real blocks. Hence, writing headers directly should only be done
  112. // in two scenarios: pure-header mode of operation (light clients), or properly
  113. // separated header/block phases (non-archive clients).
  114. func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, err error) {
  115. // Cache some values to prevent constant recalculation
  116. var (
  117. hash = header.Hash()
  118. number = header.Number.Uint64()
  119. )
  120. // Calculate the total difficulty of the header
  121. ptd := hc.GetTd(header.ParentHash, number-1)
  122. if ptd == nil {
  123. return NonStatTy, consensus.ErrUnknownAncestor
  124. }
  125. localTd := hc.GetTd(hc.currentHeaderHash, hc.CurrentHeader().Number.Uint64())
  126. externTd := new(big.Int).Add(header.Difficulty, ptd)
  127. // Irrelevant of the canonical status, write the td and header to the database
  128. if err := hc.WriteTd(hash, number, externTd); err != nil {
  129. log.Crit("Failed to write header total difficulty", "err", err)
  130. }
  131. if err := WriteHeader(hc.chainDb, header); err != nil {
  132. log.Crit("Failed to write header content", "err", err)
  133. }
  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 := GetCanonicalHash(hc.chainDb, i)
  141. if hash == (common.Hash{}) {
  142. break
  143. }
  144. 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 GetCanonicalHash(hc.chainDb, headNumber) != headHash {
  153. 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. if err := WriteCanonicalHash(hc.chainDb, hash, number); err != nil {
  160. log.Crit("Failed to insert header number", "err", err)
  161. }
  162. if err := WriteHeadHeaderHash(hc.chainDb, hash); err != nil {
  163. log.Crit("Failed to insert head header hash", "err", err)
  164. }
  165. hc.currentHeaderHash = hash
  166. hc.currentHeader.Store(types.CopyHeader(header))
  167. status = CanonStatTy
  168. } else {
  169. status = SideStatTy
  170. }
  171. hc.headerCache.Add(hash, header)
  172. hc.numberCache.Add(hash, number)
  173. return
  174. }
  175. // WhCallback is a callback function for inserting individual headers.
  176. // A callback is used for two reasons: first, in a LightChain, status should be
  177. // processed and light chain events sent, while in a BlockChain this is not
  178. // necessary since chain events are sent after inserting blocks. Second, the
  179. // header writes should be protected by the parent chain mutex individually.
  180. type WhCallback func(*types.Header) error
  181. func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  182. // Do a sanity check that the provided chain is actually ordered and linked
  183. for i := 1; i < len(chain); i++ {
  184. if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() {
  185. // Chain broke ancestry, log a messge (programming error) and skip insertion
  186. log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(),
  187. "parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash())
  188. 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,
  189. chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4])
  190. }
  191. }
  192. // Generate the list of seal verification requests, and start the parallel verifier
  193. seals := make([]bool, len(chain))
  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. seals[len(seals)-1] = true // Last should always be verified to avoid junk
  202. abort, results := hc.engine.VerifyHeaders(hc, chain, seals)
  203. defer close(abort)
  204. // Iterate over the headers and ensure they all check out
  205. for i, header := range chain {
  206. // If the chain is terminating, stop processing blocks
  207. if hc.procInterrupt() {
  208. log.Debug("Premature abort during headers verification")
  209. return 0, errors.New("aborted")
  210. }
  211. // If the header is a banned one, straight out abort
  212. if BadHashes[header.Hash()] {
  213. return i, ErrBlacklistedHash
  214. }
  215. // Otherwise wait for headers checks and ensure they pass
  216. if err := <-results; err != nil {
  217. return i, err
  218. }
  219. }
  220. return 0, nil
  221. }
  222. // InsertHeaderChain attempts to insert the given header chain in to the local
  223. // chain, possibly creating a reorg. If an error is returned, it will return the
  224. // index number of the failing header as well an error describing what went wrong.
  225. //
  226. // The verify parameter can be used to fine tune whether nonce verification
  227. // should be done or not. The reason behind the optional check is because some
  228. // of the header retrieval mechanisms already need to verfy nonces, as well as
  229. // because nonces can be verified sparsely, not needing to check each.
  230. func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) {
  231. // Collect some import statistics to report on
  232. stats := struct{ processed, ignored int }{}
  233. // All headers passed verification, import them into the database
  234. for i, header := range chain {
  235. // Short circuit insertion if shutting down
  236. if hc.procInterrupt() {
  237. log.Debug("Premature abort during headers import")
  238. return i, errors.New("aborted")
  239. }
  240. // If the header's already known, skip it, otherwise store
  241. if hc.HasHeader(header.Hash(), header.Number.Uint64()) {
  242. stats.ignored++
  243. continue
  244. }
  245. if err := writeHeader(header); err != nil {
  246. return i, err
  247. }
  248. stats.processed++
  249. }
  250. // Report some public statistics so the user has a clue what's going on
  251. last := chain[len(chain)-1]
  252. log.Info("Imported new block headers", "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  253. "number", last.Number, "hash", last.Hash(), "ignored", stats.ignored)
  254. return 0, nil
  255. }
  256. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  257. // hash, fetching towards the genesis block.
  258. func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  259. // Get the origin header from which to fetch
  260. header := hc.GetHeaderByHash(hash)
  261. if header == nil {
  262. return nil
  263. }
  264. // Iterate the headers until enough is collected or the genesis reached
  265. chain := make([]common.Hash, 0, max)
  266. for i := uint64(0); i < max; i++ {
  267. next := header.ParentHash
  268. if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil {
  269. break
  270. }
  271. chain = append(chain, next)
  272. if header.Number.Sign() == 0 {
  273. break
  274. }
  275. }
  276. return chain
  277. }
  278. // GetTd retrieves a block's total difficulty in the canonical chain from the
  279. // database by hash and number, caching it if found.
  280. func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int {
  281. // Short circuit if the td's already in the cache, retrieve otherwise
  282. if cached, ok := hc.tdCache.Get(hash); ok {
  283. return cached.(*big.Int)
  284. }
  285. td := GetTd(hc.chainDb, hash, number)
  286. if td == nil {
  287. return nil
  288. }
  289. // Cache the found body for next time and return
  290. hc.tdCache.Add(hash, td)
  291. return td
  292. }
  293. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  294. // database by hash, caching it if found.
  295. func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
  296. return hc.GetTd(hash, hc.GetBlockNumber(hash))
  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. if err := WriteTd(hc.chainDb, hash, number, td); err != nil {
  302. return err
  303. }
  304. hc.tdCache.Add(hash, new(big.Int).Set(td))
  305. return nil
  306. }
  307. // GetHeader retrieves a block header from the database by hash and number,
  308. // caching it if found.
  309. func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  310. // Short circuit if the header's already in the cache, retrieve otherwise
  311. if header, ok := hc.headerCache.Get(hash); ok {
  312. return header.(*types.Header)
  313. }
  314. header := GetHeader(hc.chainDb, hash, number)
  315. if header == nil {
  316. return nil
  317. }
  318. // Cache the found header for next time and return
  319. hc.headerCache.Add(hash, header)
  320. return header
  321. }
  322. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  323. // found.
  324. func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header {
  325. return hc.GetHeader(hash, hc.GetBlockNumber(hash))
  326. }
  327. // HasHeader checks if a block header is present in the database or not.
  328. func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
  329. if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) {
  330. return true
  331. }
  332. ok, _ := hc.chainDb.Has(headerKey(hash, number))
  333. return ok
  334. }
  335. // GetHeaderByNumber retrieves a block header from the database by number,
  336. // caching it (associated with its hash) if found.
  337. func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
  338. hash := GetCanonicalHash(hc.chainDb, number)
  339. if hash == (common.Hash{}) {
  340. return nil
  341. }
  342. return hc.GetHeader(hash, number)
  343. }
  344. // CurrentHeader retrieves the current head header of the canonical chain. The
  345. // header is retrieved from the HeaderChain's internal cache.
  346. func (hc *HeaderChain) CurrentHeader() *types.Header {
  347. return hc.currentHeader.Load().(*types.Header)
  348. }
  349. // SetCurrentHeader sets the current head header of the canonical chain.
  350. func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
  351. if err := WriteHeadHeaderHash(hc.chainDb, head.Hash()); err != nil {
  352. log.Crit("Failed to insert head header hash", "err", err)
  353. }
  354. hc.currentHeader.Store(head)
  355. hc.currentHeaderHash = head.Hash()
  356. }
  357. // DeleteCallback is a callback function that is called by SetHead before
  358. // each header is deleted.
  359. type DeleteCallback func(common.Hash, uint64)
  360. // SetHead rewinds the local chain to a new head. Everything above the new head
  361. // will be deleted and the new one set.
  362. func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback) {
  363. height := uint64(0)
  364. if hdr := hc.CurrentHeader(); hdr != nil {
  365. height = hdr.Number.Uint64()
  366. }
  367. for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() {
  368. hash := hdr.Hash()
  369. num := hdr.Number.Uint64()
  370. if delFn != nil {
  371. delFn(hash, num)
  372. }
  373. DeleteHeader(hc.chainDb, hash, num)
  374. DeleteTd(hc.chainDb, hash, num)
  375. hc.currentHeader.Store(hc.GetHeader(hdr.ParentHash, hdr.Number.Uint64()-1))
  376. }
  377. // Roll back the canonical chain numbering
  378. for i := height; i > head; i-- {
  379. DeleteCanonicalHash(hc.chainDb, i)
  380. }
  381. // Clear out any stale content from the caches
  382. hc.headerCache.Purge()
  383. hc.tdCache.Purge()
  384. hc.numberCache.Purge()
  385. if hc.CurrentHeader() == nil {
  386. hc.currentHeader.Store(hc.genesisHeader)
  387. }
  388. hc.currentHeaderHash = hc.CurrentHeader().Hash()
  389. if err := WriteHeadHeaderHash(hc.chainDb, hc.currentHeaderHash); err != nil {
  390. log.Crit("Failed to reset head header hash", "err", err)
  391. }
  392. }
  393. // SetGenesis sets a new genesis block header for the chain
  394. func (hc *HeaderChain) SetGenesis(head *types.Header) {
  395. hc.genesisHeader = head
  396. }
  397. // Config retrieves the header chain's chain configuration.
  398. func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config }
  399. // Engine retrieves the header chain's consensus engine.
  400. func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine }
  401. // GetBlock implements consensus.ChainReader, and returns nil for every input as
  402. // a header chain does not have blocks available for retrieval.
  403. func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  404. return nil
  405. }