headerchain.go 15 KB

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