chain_indexer.go 17 KB

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