headerchain.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. "fmt"
  20. "math"
  21. "math/big"
  22. mrand "math/rand"
  23. "runtime"
  24. "sync"
  25. "sync/atomic"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/ethdb"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/params"
  32. "github.com/ethereum/go-ethereum/pow"
  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 *types.Header // 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. getValidator getHeaderValidatorFn
  57. }
  58. // getHeaderValidatorFn returns a HeaderValidator interface
  59. type getHeaderValidatorFn func() HeaderValidator
  60. // NewHeaderChain creates a new HeaderChain structure.
  61. // getValidator should return the parent's validator
  62. // procInterrupt points to the parent's interrupt semaphore
  63. // wg points to the parent's shutdown wait group
  64. func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, getValidator getHeaderValidatorFn, procInterrupt func() bool) (*HeaderChain, error) {
  65. headerCache, _ := lru.New(headerCacheLimit)
  66. tdCache, _ := lru.New(tdCacheLimit)
  67. numberCache, _ := lru.New(numberCacheLimit)
  68. // Seed a fast but crypto originating random generator
  69. seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
  70. if err != nil {
  71. return nil, err
  72. }
  73. hc := &HeaderChain{
  74. config: config,
  75. chainDb: chainDb,
  76. headerCache: headerCache,
  77. tdCache: tdCache,
  78. numberCache: numberCache,
  79. procInterrupt: procInterrupt,
  80. rand: mrand.New(mrand.NewSource(seed.Int64())),
  81. getValidator: getValidator,
  82. }
  83. hc.genesisHeader = hc.GetHeaderByNumber(0)
  84. if hc.genesisHeader == nil {
  85. return nil, ErrNoGenesis
  86. }
  87. hc.currentHeader = hc.genesisHeader
  88. if head := GetHeadBlockHash(chainDb); head != (common.Hash{}) {
  89. if chead := hc.GetHeaderByHash(head); chead != nil {
  90. hc.currentHeader = chead
  91. }
  92. }
  93. hc.currentHeaderHash = hc.currentHeader.Hash()
  94. return hc, nil
  95. }
  96. // GetBlockNumber retrieves the block number belonging to the given hash
  97. // from the cache or database
  98. func (hc *HeaderChain) GetBlockNumber(hash common.Hash) uint64 {
  99. if cached, ok := hc.numberCache.Get(hash); ok {
  100. return cached.(uint64)
  101. }
  102. number := GetBlockNumber(hc.chainDb, hash)
  103. if number != missingNumber {
  104. hc.numberCache.Add(hash, number)
  105. }
  106. return number
  107. }
  108. // WriteHeader writes a header into the local chain, given that its parent is
  109. // already known. If the total difficulty of the newly inserted header becomes
  110. // greater than the current known TD, the canonical chain is re-routed.
  111. //
  112. // Note: This method is not concurrent-safe with inserting blocks simultaneously
  113. // into the chain, as side effects caused by reorganisations cannot be emulated
  114. // without the real blocks. Hence, writing headers directly should only be done
  115. // in two scenarios: pure-header mode of operation (light clients), or properly
  116. // separated header/block phases (non-archive clients).
  117. func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, err error) {
  118. // Cache some values to prevent constant recalculation
  119. var (
  120. hash = header.Hash()
  121. number = header.Number.Uint64()
  122. )
  123. // Calculate the total difficulty of the header
  124. ptd := hc.GetTd(header.ParentHash, number-1)
  125. if ptd == nil {
  126. return NonStatTy, ParentError(header.ParentHash)
  127. }
  128. localTd := hc.GetTd(hc.currentHeaderHash, hc.currentHeader.Number.Uint64())
  129. externTd := new(big.Int).Add(header.Difficulty, ptd)
  130. // Irrelevant of the canonical status, write the td and header to the database
  131. if err := hc.WriteTd(hash, number, externTd); err != nil {
  132. log.Crit("Failed to write header total difficulty", "err", err)
  133. }
  134. if err := WriteHeader(hc.chainDb, header); err != nil {
  135. log.Crit("Failed to write header content", "err", err)
  136. }
  137. // If the total difficulty is higher than our known, add it to the canonical chain
  138. // Second clause in the if statement reduces the vulnerability to selfish mining.
  139. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  140. if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) {
  141. // Delete any canonical number assignments above the new head
  142. for i := number + 1; ; i++ {
  143. hash := GetCanonicalHash(hc.chainDb, i)
  144. if hash == (common.Hash{}) {
  145. break
  146. }
  147. DeleteCanonicalHash(hc.chainDb, i)
  148. }
  149. // Overwrite any stale canonical number assignments
  150. var (
  151. headHash = header.ParentHash
  152. headNumber = header.Number.Uint64() - 1
  153. headHeader = hc.GetHeader(headHash, headNumber)
  154. )
  155. for GetCanonicalHash(hc.chainDb, headNumber) != headHash {
  156. WriteCanonicalHash(hc.chainDb, headHash, headNumber)
  157. headHash = headHeader.ParentHash
  158. headNumber = headHeader.Number.Uint64() - 1
  159. headHeader = hc.GetHeader(headHash, headNumber)
  160. }
  161. // Extend the canonical chain with the new header
  162. if err := WriteCanonicalHash(hc.chainDb, hash, number); err != nil {
  163. log.Crit("Failed to insert header number", "err", err)
  164. }
  165. if err := WriteHeadHeaderHash(hc.chainDb, hash); err != nil {
  166. log.Crit("Failed to insert head header hash", "err", err)
  167. }
  168. hc.currentHeaderHash, hc.currentHeader = hash, types.CopyHeader(header)
  169. status = CanonStatTy
  170. } else {
  171. status = SideStatTy
  172. }
  173. hc.headerCache.Add(hash, header)
  174. hc.numberCache.Add(hash, number)
  175. return
  176. }
  177. // WhCallback is a callback function for inserting individual headers.
  178. // A callback is used for two reasons: first, in a LightChain, status should be
  179. // processed and light chain events sent, while in a BlockChain this is not
  180. // necessary since chain events are sent after inserting blocks. Second, the
  181. // header writes should be protected by the parent chain mutex individually.
  182. type WhCallback func(*types.Header) error
  183. // InsertHeaderChain attempts to insert the given header chain in to the local
  184. // chain, possibly creating a reorg. If an error is returned, it will return the
  185. // index number of the failing header as well an error describing what went wrong.
  186. //
  187. // The verify parameter can be used to fine tune whether nonce verification
  188. // should be done or not. The reason behind the optional check is because some
  189. // of the header retrieval mechanisms already need to verfy nonces, as well as
  190. // because nonces can be verified sparsely, not needing to check each.
  191. func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  192. // Do a sanity check that the provided chain is actually ordered and linked
  193. for i := 1; i < len(chain); i++ {
  194. if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() {
  195. // Chain broke ancestry, log a messge (programming error) and skip insertion
  196. log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(),
  197. "parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash())
  198. 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,
  199. chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4])
  200. }
  201. }
  202. // Generate the list of headers that should be POW verified
  203. verify := make([]bool, len(chain))
  204. for i := 0; i < len(verify)/checkFreq; i++ {
  205. index := i*checkFreq + hc.rand.Intn(checkFreq)
  206. if index >= len(verify) {
  207. index = len(verify) - 1
  208. }
  209. verify[index] = true
  210. }
  211. verify[len(verify)-1] = true // Last should always be verified to avoid junk
  212. // Create the header verification task queue and worker functions
  213. tasks := make(chan int, len(chain))
  214. for i := 0; i < len(chain); i++ {
  215. tasks <- i
  216. }
  217. close(tasks)
  218. errs, failed := make([]error, len(tasks)), int32(0)
  219. process := func(worker int) {
  220. for index := range tasks {
  221. header, hash := chain[index], chain[index].Hash()
  222. // Short circuit insertion if shutting down or processing failed
  223. if hc.procInterrupt() {
  224. return
  225. }
  226. if atomic.LoadInt32(&failed) > 0 {
  227. return
  228. }
  229. // Short circuit if the header is bad or already known
  230. if BadHashes[hash] {
  231. errs[index] = BadHashError(hash)
  232. atomic.AddInt32(&failed, 1)
  233. return
  234. }
  235. if hc.HasHeader(hash) {
  236. continue
  237. }
  238. // Verify that the header honors the chain parameters
  239. checkPow := verify[index]
  240. var err error
  241. if index == 0 {
  242. err = hc.getValidator().ValidateHeader(header, hc.GetHeader(header.ParentHash, header.Number.Uint64()-1), checkPow)
  243. } else {
  244. err = hc.getValidator().ValidateHeader(header, chain[index-1], checkPow)
  245. }
  246. if err != nil {
  247. errs[index] = err
  248. atomic.AddInt32(&failed, 1)
  249. return
  250. }
  251. }
  252. }
  253. // Start as many worker threads as goroutines allowed
  254. pending := new(sync.WaitGroup)
  255. for i := 0; i < runtime.GOMAXPROCS(0); i++ {
  256. pending.Add(1)
  257. go func(id int) {
  258. defer pending.Done()
  259. process(id)
  260. }(i)
  261. }
  262. pending.Wait()
  263. // If anything failed, report
  264. if failed > 0 {
  265. for i, err := range errs {
  266. if err != nil {
  267. return i, err
  268. }
  269. }
  270. }
  271. return 0, nil
  272. }
  273. func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) {
  274. // Collect some import statistics to report on
  275. stats := struct{ processed, ignored int }{}
  276. // All headers passed verification, import them into the database
  277. for i, header := range chain {
  278. // Short circuit insertion if shutting down
  279. if hc.procInterrupt() {
  280. log.Debug("Premature abort during headers processing")
  281. break
  282. }
  283. hash := header.Hash()
  284. // If the header's already known, skip it, otherwise store
  285. if hc.HasHeader(hash) {
  286. stats.ignored++
  287. continue
  288. }
  289. if err := writeHeader(header); err != nil {
  290. return i, err
  291. }
  292. stats.processed++
  293. }
  294. // Report some public statistics so the user has a clue what's going on
  295. last := chain[len(chain)-1]
  296. log.Info("Imported new block headers", "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  297. "number", last.Number, "hash", last.Hash(), "ignored", stats.ignored)
  298. return 0, nil
  299. }
  300. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  301. // hash, fetching towards the genesis block.
  302. func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  303. // Get the origin header from which to fetch
  304. header := hc.GetHeaderByHash(hash)
  305. if header == nil {
  306. return nil
  307. }
  308. // Iterate the headers until enough is collected or the genesis reached
  309. chain := make([]common.Hash, 0, max)
  310. for i := uint64(0); i < max; i++ {
  311. next := header.ParentHash
  312. if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil {
  313. break
  314. }
  315. chain = append(chain, next)
  316. if header.Number.Sign() == 0 {
  317. break
  318. }
  319. }
  320. return chain
  321. }
  322. // GetTd retrieves a block's total difficulty in the canonical chain from the
  323. // database by hash and number, caching it if found.
  324. func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int {
  325. // Short circuit if the td's already in the cache, retrieve otherwise
  326. if cached, ok := hc.tdCache.Get(hash); ok {
  327. return cached.(*big.Int)
  328. }
  329. td := GetTd(hc.chainDb, hash, number)
  330. if td == nil {
  331. return nil
  332. }
  333. // Cache the found body for next time and return
  334. hc.tdCache.Add(hash, td)
  335. return td
  336. }
  337. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  338. // database by hash, caching it if found.
  339. func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
  340. return hc.GetTd(hash, hc.GetBlockNumber(hash))
  341. }
  342. // WriteTd stores a block's total difficulty into the database, also caching it
  343. // along the way.
  344. func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) error {
  345. if err := WriteTd(hc.chainDb, hash, number, td); err != nil {
  346. return err
  347. }
  348. hc.tdCache.Add(hash, new(big.Int).Set(td))
  349. return nil
  350. }
  351. // GetHeader retrieves a block header from the database by hash and number,
  352. // caching it if found.
  353. func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  354. // Short circuit if the header's already in the cache, retrieve otherwise
  355. if header, ok := hc.headerCache.Get(hash); ok {
  356. return header.(*types.Header)
  357. }
  358. header := GetHeader(hc.chainDb, hash, number)
  359. if header == nil {
  360. return nil
  361. }
  362. // Cache the found header for next time and return
  363. hc.headerCache.Add(hash, header)
  364. return header
  365. }
  366. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  367. // found.
  368. func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header {
  369. return hc.GetHeader(hash, hc.GetBlockNumber(hash))
  370. }
  371. // HasHeader checks if a block header is present in the database or not, caching
  372. // it if present.
  373. func (hc *HeaderChain) HasHeader(hash common.Hash) bool {
  374. return hc.GetHeaderByHash(hash) != nil
  375. }
  376. // GetHeaderByNumber retrieves a block header from the database by number,
  377. // caching it (associated with its hash) if found.
  378. func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
  379. hash := GetCanonicalHash(hc.chainDb, number)
  380. if hash == (common.Hash{}) {
  381. return nil
  382. }
  383. return hc.GetHeader(hash, number)
  384. }
  385. // CurrentHeader retrieves the current head header of the canonical chain. The
  386. // header is retrieved from the HeaderChain's internal cache.
  387. func (hc *HeaderChain) CurrentHeader() *types.Header {
  388. return hc.currentHeader
  389. }
  390. // SetCurrentHeader sets the current head header of the canonical chain.
  391. func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
  392. if err := WriteHeadHeaderHash(hc.chainDb, head.Hash()); err != nil {
  393. log.Crit("Failed to insert head header hash", "err", err)
  394. }
  395. hc.currentHeader = head
  396. hc.currentHeaderHash = head.Hash()
  397. }
  398. // DeleteCallback is a callback function that is called by SetHead before
  399. // each header is deleted.
  400. type DeleteCallback func(common.Hash, uint64)
  401. // SetHead rewinds the local chain to a new head. Everything above the new head
  402. // will be deleted and the new one set.
  403. func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback) {
  404. height := uint64(0)
  405. if hc.currentHeader != nil {
  406. height = hc.currentHeader.Number.Uint64()
  407. }
  408. for hc.currentHeader != nil && hc.currentHeader.Number.Uint64() > head {
  409. hash := hc.currentHeader.Hash()
  410. num := hc.currentHeader.Number.Uint64()
  411. if delFn != nil {
  412. delFn(hash, num)
  413. }
  414. DeleteHeader(hc.chainDb, hash, num)
  415. DeleteTd(hc.chainDb, hash, num)
  416. hc.currentHeader = hc.GetHeader(hc.currentHeader.ParentHash, hc.currentHeader.Number.Uint64()-1)
  417. }
  418. // Roll back the canonical chain numbering
  419. for i := height; i > head; i-- {
  420. DeleteCanonicalHash(hc.chainDb, i)
  421. }
  422. // Clear out any stale content from the caches
  423. hc.headerCache.Purge()
  424. hc.tdCache.Purge()
  425. hc.numberCache.Purge()
  426. if hc.currentHeader == nil {
  427. hc.currentHeader = hc.genesisHeader
  428. }
  429. hc.currentHeaderHash = hc.currentHeader.Hash()
  430. if err := WriteHeadHeaderHash(hc.chainDb, hc.currentHeaderHash); err != nil {
  431. log.Crit("Failed to reset head header hash", "err", err)
  432. }
  433. }
  434. // SetGenesis sets a new genesis block header for the chain
  435. func (hc *HeaderChain) SetGenesis(head *types.Header) {
  436. hc.genesisHeader = head
  437. }
  438. // headerValidator is responsible for validating block headers
  439. //
  440. // headerValidator implements HeaderValidator.
  441. type headerValidator struct {
  442. config *params.ChainConfig
  443. hc *HeaderChain // Canonical header chain
  444. Pow pow.PoW // Proof of work used for validating
  445. }
  446. // NewBlockValidator returns a new block validator which is safe for re-use
  447. func NewHeaderValidator(config *params.ChainConfig, chain *HeaderChain, pow pow.PoW) HeaderValidator {
  448. return &headerValidator{
  449. config: config,
  450. Pow: pow,
  451. hc: chain,
  452. }
  453. }
  454. // ValidateHeader validates the given header and, depending on the pow arg,
  455. // checks the proof of work of the given header. Returns an error if the
  456. // validation failed.
  457. func (v *headerValidator) ValidateHeader(header, parent *types.Header, checkPow bool) error {
  458. // Short circuit if the parent is missing.
  459. if parent == nil {
  460. return ParentError(header.ParentHash)
  461. }
  462. // Short circuit if the header's already known or its parent missing
  463. if v.hc.HasHeader(header.Hash()) {
  464. return nil
  465. }
  466. return ValidateHeader(v.config, v.Pow, header, parent, checkPow, false)
  467. }