headerchain.go 17 KB

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