headerchain.go 17 KB

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