chain_indexer.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. // Copyright 2017 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. "context"
  19. "encoding/binary"
  20. "fmt"
  21. "sync"
  22. "sync/atomic"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/core/rawdb"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/event"
  29. "github.com/ethereum/go-ethereum/log"
  30. )
  31. // ChainIndexerBackend defines the methods needed to process chain segments in
  32. // the background and write the segment results into the database. These can be
  33. // used to create filter blooms or CHTs.
  34. type ChainIndexerBackend interface {
  35. // Reset initiates the processing of a new chain segment, potentially terminating
  36. // any partially completed operations (in case of a reorg).
  37. Reset(ctx context.Context, section uint64, prevHead common.Hash) error
  38. // Process crunches through the next header in the chain segment. The caller
  39. // will ensure a sequential order of headers.
  40. Process(ctx context.Context, header *types.Header) error
  41. // Commit finalizes the section metadata and stores it into the database.
  42. Commit() error
  43. // Prune deletes the chain index older than the given threshold.
  44. Prune(threshold uint64) error
  45. }
  46. // ChainIndexerChain interface is used for connecting the indexer to a blockchain
  47. type ChainIndexerChain interface {
  48. // CurrentHeader retrieves the latest locally known header.
  49. CurrentHeader() *types.Header
  50. // SubscribeChainHeadEvent subscribes to new head header notifications.
  51. SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription
  52. }
  53. // ChainIndexer does a post-processing job for equally sized sections of the
  54. // canonical chain (like BlooomBits and CHT structures). A ChainIndexer is
  55. // connected to the blockchain through the event system by starting a
  56. // ChainHeadEventLoop in a goroutine.
  57. //
  58. // Further child ChainIndexers can be added which use the output of the parent
  59. // section indexer. These child indexers receive new head notifications only
  60. // after an entire section has been finished or in case of rollbacks that might
  61. // affect already finished sections.
  62. type ChainIndexer struct {
  63. chainDb ethdb.Database // Chain database to index the data from
  64. indexDb ethdb.Database // Prefixed table-view of the db to write index metadata into
  65. backend ChainIndexerBackend // Background processor generating the index data content
  66. children []*ChainIndexer // Child indexers to cascade chain updates to
  67. active uint32 // Flag whether the event loop was started
  68. update chan struct{} // Notification channel that headers should be processed
  69. quit chan chan error // Quit channel to tear down running goroutines
  70. ctx context.Context
  71. ctxCancel func()
  72. sectionSize uint64 // Number of blocks in a single chain segment to process
  73. confirmsReq uint64 // Number of confirmations before processing a completed segment
  74. storedSections uint64 // Number of sections successfully indexed into the database
  75. knownSections uint64 // Number of sections known to be complete (block wise)
  76. cascadedHead uint64 // Block number of the last completed section cascaded to subindexers
  77. checkpointSections uint64 // Number of sections covered by the checkpoint
  78. checkpointHead common.Hash // Section head belonging to the checkpoint
  79. throttling time.Duration // Disk throttling to prevent a heavy upgrade from hogging resources
  80. log log.Logger
  81. lock sync.Mutex
  82. }
  83. // NewChainIndexer creates a new chain indexer to do background processing on
  84. // chain segments of a given size after certain number of confirmations passed.
  85. // The throttling parameter might be used to prevent database thrashing.
  86. func NewChainIndexer(chainDb ethdb.Database, indexDb ethdb.Database, backend ChainIndexerBackend, section, confirm uint64, throttling time.Duration, kind string) *ChainIndexer {
  87. c := &ChainIndexer{
  88. chainDb: chainDb,
  89. indexDb: indexDb,
  90. backend: backend,
  91. update: make(chan struct{}, 1),
  92. quit: make(chan chan error),
  93. sectionSize: section,
  94. confirmsReq: confirm,
  95. throttling: throttling,
  96. log: log.New("type", kind),
  97. }
  98. // Initialize database dependent fields and start the updater
  99. c.loadValidSections()
  100. c.ctx, c.ctxCancel = context.WithCancel(context.Background())
  101. go c.updateLoop()
  102. return c
  103. }
  104. // AddCheckpoint adds a checkpoint. Sections are never processed and the chain
  105. // is not expected to be available before this point. The indexer assumes that
  106. // the backend has sufficient information available to process subsequent sections.
  107. //
  108. // Note: knownSections == 0 and storedSections == checkpointSections until
  109. // syncing reaches the checkpoint
  110. func (c *ChainIndexer) AddCheckpoint(section uint64, shead common.Hash) {
  111. c.lock.Lock()
  112. defer c.lock.Unlock()
  113. // Short circuit if the given checkpoint is below than local's.
  114. if c.checkpointSections >= section+1 || section < c.storedSections {
  115. return
  116. }
  117. c.checkpointSections = section + 1
  118. c.checkpointHead = shead
  119. c.setSectionHead(section, shead)
  120. c.setValidSections(section + 1)
  121. }
  122. // Start creates a goroutine to feed chain head events into the indexer for
  123. // cascading background processing. Children do not need to be started, they
  124. // are notified about new events by their parents.
  125. func (c *ChainIndexer) Start(chain ChainIndexerChain) {
  126. events := make(chan ChainHeadEvent, 10)
  127. sub := chain.SubscribeChainHeadEvent(events)
  128. go c.eventLoop(chain.CurrentHeader(), events, sub)
  129. }
  130. // Close tears down all goroutines belonging to the indexer and returns any error
  131. // that might have occurred internally.
  132. func (c *ChainIndexer) Close() error {
  133. var errs []error
  134. c.ctxCancel()
  135. // Tear down the primary update loop
  136. errc := make(chan error)
  137. c.quit <- errc
  138. if err := <-errc; err != nil {
  139. errs = append(errs, err)
  140. }
  141. // If needed, tear down the secondary event loop
  142. if atomic.LoadUint32(&c.active) != 0 {
  143. c.quit <- errc
  144. if err := <-errc; err != nil {
  145. errs = append(errs, err)
  146. }
  147. }
  148. // Close all children
  149. for _, child := range c.children {
  150. if err := child.Close(); err != nil {
  151. errs = append(errs, err)
  152. }
  153. }
  154. // Return any failures
  155. switch {
  156. case len(errs) == 0:
  157. return nil
  158. case len(errs) == 1:
  159. return errs[0]
  160. default:
  161. return fmt.Errorf("%v", errs)
  162. }
  163. }
  164. // eventLoop is a secondary - optional - event loop of the indexer which is only
  165. // started for the outermost indexer to push chain head events into a processing
  166. // queue.
  167. func (c *ChainIndexer) eventLoop(currentHeader *types.Header, events chan ChainHeadEvent, sub event.Subscription) {
  168. // Mark the chain indexer as active, requiring an additional teardown
  169. atomic.StoreUint32(&c.active, 1)
  170. defer sub.Unsubscribe()
  171. // Fire the initial new head event to start any outstanding processing
  172. c.newHead(currentHeader.Number.Uint64(), false)
  173. var (
  174. prevHeader = currentHeader
  175. prevHash = currentHeader.Hash()
  176. )
  177. for {
  178. select {
  179. case errc := <-c.quit:
  180. // Chain indexer terminating, report no failure and abort
  181. errc <- nil
  182. return
  183. case ev, ok := <-events:
  184. // Received a new event, ensure it's not nil (closing) and update
  185. if !ok {
  186. errc := <-c.quit
  187. errc <- nil
  188. return
  189. }
  190. header := ev.Block.Header()
  191. if header.ParentHash != prevHash {
  192. // Reorg to the common ancestor if needed (might not exist in light sync mode, skip reorg then)
  193. // TODO(karalabe, zsfelfoldi): This seems a bit brittle, can we detect this case explicitly?
  194. if rawdb.ReadCanonicalHash(c.chainDb, prevHeader.Number.Uint64()) != prevHash {
  195. if h := rawdb.FindCommonAncestor(c.chainDb, prevHeader, header); h != nil {
  196. c.newHead(h.Number.Uint64(), true)
  197. }
  198. }
  199. }
  200. c.newHead(header.Number.Uint64(), false)
  201. prevHeader, prevHash = header, header.Hash()
  202. }
  203. }
  204. }
  205. // newHead notifies the indexer about new chain heads and/or reorgs.
  206. func (c *ChainIndexer) newHead(head uint64, reorg bool) {
  207. c.lock.Lock()
  208. defer c.lock.Unlock()
  209. // If a reorg happened, invalidate all sections until that point
  210. if reorg {
  211. // Revert the known section number to the reorg point
  212. known := (head + 1) / c.sectionSize
  213. stored := known
  214. if known < c.checkpointSections {
  215. known = 0
  216. }
  217. if stored < c.checkpointSections {
  218. stored = c.checkpointSections
  219. }
  220. if known < c.knownSections {
  221. c.knownSections = known
  222. }
  223. // Revert the stored sections from the database to the reorg point
  224. if stored < c.storedSections {
  225. c.setValidSections(stored)
  226. }
  227. // Update the new head number to the finalized section end and notify children
  228. head = known * c.sectionSize
  229. if head < c.cascadedHead {
  230. c.cascadedHead = head
  231. for _, child := range c.children {
  232. child.newHead(c.cascadedHead, true)
  233. }
  234. }
  235. return
  236. }
  237. // No reorg, calculate the number of newly known sections and update if high enough
  238. var sections uint64
  239. if head >= c.confirmsReq {
  240. sections = (head + 1 - c.confirmsReq) / c.sectionSize
  241. if sections < c.checkpointSections {
  242. sections = 0
  243. }
  244. if sections > c.knownSections {
  245. if c.knownSections < c.checkpointSections {
  246. // syncing reached the checkpoint, verify section head
  247. syncedHead := rawdb.ReadCanonicalHash(c.chainDb, c.checkpointSections*c.sectionSize-1)
  248. if syncedHead != c.checkpointHead {
  249. c.log.Error("Synced chain does not match checkpoint", "number", c.checkpointSections*c.sectionSize-1, "expected", c.checkpointHead, "synced", syncedHead)
  250. return
  251. }
  252. }
  253. c.knownSections = sections
  254. select {
  255. case c.update <- struct{}{}:
  256. default:
  257. }
  258. }
  259. }
  260. }
  261. // updateLoop is the main event loop of the indexer which pushes chain segments
  262. // down into the processing backend.
  263. func (c *ChainIndexer) updateLoop() {
  264. var (
  265. updating bool
  266. updated time.Time
  267. )
  268. for {
  269. select {
  270. case errc := <-c.quit:
  271. // Chain indexer terminating, report no failure and abort
  272. errc <- nil
  273. return
  274. case <-c.update:
  275. // Section headers completed (or rolled back), update the index
  276. c.lock.Lock()
  277. if c.knownSections > c.storedSections {
  278. // Periodically print an upgrade log message to the user
  279. if time.Since(updated) > 8*time.Second {
  280. if c.knownSections > c.storedSections+1 {
  281. updating = true
  282. c.log.Info("Upgrading chain index", "percentage", c.storedSections*100/c.knownSections)
  283. }
  284. updated = time.Now()
  285. }
  286. // Cache the current section count and head to allow unlocking the mutex
  287. c.verifyLastHead()
  288. section := c.storedSections
  289. var oldHead common.Hash
  290. if section > 0 {
  291. oldHead = c.SectionHead(section - 1)
  292. }
  293. // Process the newly defined section in the background
  294. c.lock.Unlock()
  295. newHead, err := c.processSection(section, oldHead)
  296. if err != nil {
  297. select {
  298. case <-c.ctx.Done():
  299. <-c.quit <- nil
  300. return
  301. default:
  302. }
  303. c.log.Error("Section processing failed", "error", err)
  304. }
  305. c.lock.Lock()
  306. // If processing succeeded and no reorgs occurred, mark the section completed
  307. if err == nil && (section == 0 || oldHead == c.SectionHead(section-1)) {
  308. c.setSectionHead(section, newHead)
  309. c.setValidSections(section + 1)
  310. if c.storedSections == c.knownSections && updating {
  311. updating = false
  312. c.log.Info("Finished upgrading chain index")
  313. }
  314. c.cascadedHead = c.storedSections*c.sectionSize - 1
  315. for _, child := range c.children {
  316. c.log.Trace("Cascading chain index update", "head", c.cascadedHead)
  317. child.newHead(c.cascadedHead, false)
  318. }
  319. } else {
  320. // If processing failed, don't retry until further notification
  321. c.log.Debug("Chain index processing failed", "section", section, "err", err)
  322. c.verifyLastHead()
  323. c.knownSections = c.storedSections
  324. }
  325. }
  326. // If there are still further sections to process, reschedule
  327. if c.knownSections > c.storedSections {
  328. time.AfterFunc(c.throttling, func() {
  329. select {
  330. case c.update <- struct{}{}:
  331. default:
  332. }
  333. })
  334. }
  335. c.lock.Unlock()
  336. }
  337. }
  338. }
  339. // processSection processes an entire section by calling backend functions while
  340. // ensuring the continuity of the passed headers. Since the chain mutex is not
  341. // held while processing, the continuity can be broken by a long reorg, in which
  342. // case the function returns with an error.
  343. func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (common.Hash, error) {
  344. c.log.Trace("Processing new chain section", "section", section)
  345. // Reset and partial processing
  346. if err := c.backend.Reset(c.ctx, section, lastHead); err != nil {
  347. c.setValidSections(0)
  348. return common.Hash{}, err
  349. }
  350. for number := section * c.sectionSize; number < (section+1)*c.sectionSize; number++ {
  351. hash := rawdb.ReadCanonicalHash(c.chainDb, number)
  352. if hash == (common.Hash{}) {
  353. return common.Hash{}, fmt.Errorf("canonical block #%d unknown", number)
  354. }
  355. header := rawdb.ReadHeader(c.chainDb, hash, number)
  356. if header == nil {
  357. return common.Hash{}, fmt.Errorf("block #%d [%x..] not found", number, hash[:4])
  358. } else if header.ParentHash != lastHead {
  359. return common.Hash{}, fmt.Errorf("chain reorged during section processing")
  360. }
  361. if err := c.backend.Process(c.ctx, header); err != nil {
  362. return common.Hash{}, err
  363. }
  364. lastHead = header.Hash()
  365. }
  366. if err := c.backend.Commit(); err != nil {
  367. return common.Hash{}, err
  368. }
  369. return lastHead, nil
  370. }
  371. // verifyLastHead compares last stored section head with the corresponding block hash in the
  372. // actual canonical chain and rolls back reorged sections if necessary to ensure that stored
  373. // sections are all valid
  374. func (c *ChainIndexer) verifyLastHead() {
  375. for c.storedSections > 0 && c.storedSections > c.checkpointSections {
  376. if c.SectionHead(c.storedSections-1) == rawdb.ReadCanonicalHash(c.chainDb, c.storedSections*c.sectionSize-1) {
  377. return
  378. }
  379. c.setValidSections(c.storedSections - 1)
  380. }
  381. }
  382. // Sections returns the number of processed sections maintained by the indexer
  383. // and also the information about the last header indexed for potential canonical
  384. // verifications.
  385. func (c *ChainIndexer) Sections() (uint64, uint64, common.Hash) {
  386. c.lock.Lock()
  387. defer c.lock.Unlock()
  388. c.verifyLastHead()
  389. return c.storedSections, c.storedSections*c.sectionSize - 1, c.SectionHead(c.storedSections - 1)
  390. }
  391. // AddChildIndexer adds a child ChainIndexer that can use the output of this one
  392. func (c *ChainIndexer) AddChildIndexer(indexer *ChainIndexer) {
  393. if indexer == c {
  394. panic("can't add indexer as a child of itself")
  395. }
  396. c.lock.Lock()
  397. defer c.lock.Unlock()
  398. c.children = append(c.children, indexer)
  399. // Cascade any pending updates to new children too
  400. sections := c.storedSections
  401. if c.knownSections < sections {
  402. // if a section is "stored" but not "known" then it is a checkpoint without
  403. // available chain data so we should not cascade it yet
  404. sections = c.knownSections
  405. }
  406. if sections > 0 {
  407. indexer.newHead(sections*c.sectionSize-1, false)
  408. }
  409. }
  410. // Prune deletes all chain data older than given threshold.
  411. func (c *ChainIndexer) Prune(threshold uint64) error {
  412. return c.backend.Prune(threshold)
  413. }
  414. // loadValidSections reads the number of valid sections from the index database
  415. // and caches is into the local state.
  416. func (c *ChainIndexer) loadValidSections() {
  417. data, _ := c.indexDb.Get([]byte("count"))
  418. if len(data) == 8 {
  419. c.storedSections = binary.BigEndian.Uint64(data)
  420. }
  421. }
  422. // setValidSections writes the number of valid sections to the index database
  423. func (c *ChainIndexer) setValidSections(sections uint64) {
  424. // Set the current number of valid sections in the database
  425. var data [8]byte
  426. binary.BigEndian.PutUint64(data[:], sections)
  427. c.indexDb.Put([]byte("count"), data[:])
  428. // Remove any reorged sections, caching the valids in the mean time
  429. for c.storedSections > sections {
  430. c.storedSections--
  431. c.removeSectionHead(c.storedSections)
  432. }
  433. c.storedSections = sections // needed if new > old
  434. }
  435. // SectionHead retrieves the last block hash of a processed section from the
  436. // index database.
  437. func (c *ChainIndexer) SectionHead(section uint64) common.Hash {
  438. var data [8]byte
  439. binary.BigEndian.PutUint64(data[:], section)
  440. hash, _ := c.indexDb.Get(append([]byte("shead"), data[:]...))
  441. if len(hash) == len(common.Hash{}) {
  442. return common.BytesToHash(hash)
  443. }
  444. return common.Hash{}
  445. }
  446. // setSectionHead writes the last block hash of a processed section to the index
  447. // database.
  448. func (c *ChainIndexer) setSectionHead(section uint64, hash common.Hash) {
  449. var data [8]byte
  450. binary.BigEndian.PutUint64(data[:], section)
  451. c.indexDb.Put(append([]byte("shead"), data[:]...), hash.Bytes())
  452. }
  453. // removeSectionHead removes the reference to a processed section from the index
  454. // database.
  455. func (c *ChainIndexer) removeSectionHead(section uint64) {
  456. var data [8]byte
  457. binary.BigEndian.PutUint64(data[:], section)
  458. c.indexDb.Delete(append([]byte("shead"), data[:]...))
  459. }