headerchain.go 18 KB

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