chain_indexer.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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, 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. c.checkpointSections = section + 1
  112. c.checkpointHead = shead
  113. if section < c.storedSections {
  114. return
  115. }
  116. c.setSectionHead(section, shead)
  117. c.setValidSections(section + 1)
  118. }
  119. // Start creates a goroutine to feed chain head events into the indexer for
  120. // cascading background processing. Children do not need to be started, they
  121. // are notified about new events by their parents.
  122. func (c *ChainIndexer) Start(chain ChainIndexerChain) {
  123. events := make(chan ChainHeadEvent, 10)
  124. sub := chain.SubscribeChainHeadEvent(events)
  125. go c.eventLoop(chain.CurrentHeader(), events, sub)
  126. }
  127. // Close tears down all goroutines belonging to the indexer and returns any error
  128. // that might have occurred internally.
  129. func (c *ChainIndexer) Close() error {
  130. var errs []error
  131. c.ctxCancel()
  132. // Tear down the primary update loop
  133. errc := make(chan error)
  134. c.quit <- errc
  135. if err := <-errc; err != nil {
  136. errs = append(errs, err)
  137. }
  138. // If needed, tear down the secondary event loop
  139. if atomic.LoadUint32(&c.active) != 0 {
  140. c.quit <- errc
  141. if err := <-errc; err != nil {
  142. errs = append(errs, err)
  143. }
  144. }
  145. // Close all children
  146. for _, child := range c.children {
  147. if err := child.Close(); err != nil {
  148. errs = append(errs, err)
  149. }
  150. }
  151. // Return any failures
  152. switch {
  153. case len(errs) == 0:
  154. return nil
  155. case len(errs) == 1:
  156. return errs[0]
  157. default:
  158. return fmt.Errorf("%v", errs)
  159. }
  160. }
  161. // eventLoop is a secondary - optional - event loop of the indexer which is only
  162. // started for the outermost indexer to push chain head events into a processing
  163. // queue.
  164. func (c *ChainIndexer) eventLoop(currentHeader *types.Header, events chan ChainHeadEvent, sub event.Subscription) {
  165. // Mark the chain indexer as active, requiring an additional teardown
  166. atomic.StoreUint32(&c.active, 1)
  167. defer sub.Unsubscribe()
  168. // Fire the initial new head event to start any outstanding processing
  169. c.newHead(currentHeader.Number.Uint64(), false)
  170. var (
  171. prevHeader = currentHeader
  172. prevHash = currentHeader.Hash()
  173. )
  174. for {
  175. select {
  176. case errc := <-c.quit:
  177. // Chain indexer terminating, report no failure and abort
  178. errc <- nil
  179. return
  180. case ev, ok := <-events:
  181. // Received a new event, ensure it's not nil (closing) and update
  182. if !ok {
  183. errc := <-c.quit
  184. errc <- nil
  185. return
  186. }
  187. header := ev.Block.Header()
  188. if header.ParentHash != prevHash {
  189. // Reorg to the common ancestor if needed (might not exist in light sync mode, skip reorg then)
  190. // TODO(karalabe, zsfelfoldi): This seems a bit brittle, can we detect this case explicitly?
  191. if rawdb.ReadCanonicalHash(c.chainDb, prevHeader.Number.Uint64()) != prevHash {
  192. if h := rawdb.FindCommonAncestor(c.chainDb, prevHeader, header); h != nil {
  193. c.newHead(h.Number.Uint64(), true)
  194. }
  195. }
  196. }
  197. c.newHead(header.Number.Uint64(), false)
  198. prevHeader, prevHash = header, header.Hash()
  199. }
  200. }
  201. }
  202. // newHead notifies the indexer about new chain heads and/or reorgs.
  203. func (c *ChainIndexer) newHead(head uint64, reorg bool) {
  204. c.lock.Lock()
  205. defer c.lock.Unlock()
  206. // If a reorg happened, invalidate all sections until that point
  207. if reorg {
  208. // Revert the known section number to the reorg point
  209. known := head / c.sectionSize
  210. stored := known
  211. if known < c.checkpointSections {
  212. known = 0
  213. }
  214. if stored < c.checkpointSections {
  215. stored = c.checkpointSections
  216. }
  217. if known < c.knownSections {
  218. c.knownSections = known
  219. }
  220. // Revert the stored sections from the database to the reorg point
  221. if stored < c.storedSections {
  222. c.setValidSections(stored)
  223. }
  224. // Update the new head number to the finalized section end and notify children
  225. head = known * c.sectionSize
  226. if head < c.cascadedHead {
  227. c.cascadedHead = head
  228. for _, child := range c.children {
  229. child.newHead(c.cascadedHead, true)
  230. }
  231. }
  232. return
  233. }
  234. // No reorg, calculate the number of newly known sections and update if high enough
  235. var sections uint64
  236. if head >= c.confirmsReq {
  237. sections = (head + 1 - c.confirmsReq) / c.sectionSize
  238. if sections < c.checkpointSections {
  239. sections = 0
  240. }
  241. if sections > c.knownSections {
  242. if c.knownSections < c.checkpointSections {
  243. // syncing reached the checkpoint, verify section head
  244. syncedHead := rawdb.ReadCanonicalHash(c.chainDb, c.checkpointSections*c.sectionSize-1)
  245. if syncedHead != c.checkpointHead {
  246. c.log.Error("Synced chain does not match checkpoint", "number", c.checkpointSections*c.sectionSize-1, "expected", c.checkpointHead, "synced", syncedHead)
  247. return
  248. }
  249. }
  250. c.knownSections = sections
  251. select {
  252. case c.update <- struct{}{}:
  253. default:
  254. }
  255. }
  256. }
  257. }
  258. // updateLoop is the main event loop of the indexer which pushes chain segments
  259. // down into the processing backend.
  260. func (c *ChainIndexer) updateLoop() {
  261. var (
  262. updating bool
  263. updated time.Time
  264. )
  265. for {
  266. select {
  267. case errc := <-c.quit:
  268. // Chain indexer terminating, report no failure and abort
  269. errc <- nil
  270. return
  271. case <-c.update:
  272. // Section headers completed (or rolled back), update the index
  273. c.lock.Lock()
  274. if c.knownSections > c.storedSections {
  275. // Periodically print an upgrade log message to the user
  276. if time.Since(updated) > 8*time.Second {
  277. if c.knownSections > c.storedSections+1 {
  278. updating = true
  279. c.log.Info("Upgrading chain index", "percentage", c.storedSections*100/c.knownSections)
  280. }
  281. updated = time.Now()
  282. }
  283. // Cache the current section count and head to allow unlocking the mutex
  284. section := c.storedSections
  285. var oldHead common.Hash
  286. if section > 0 {
  287. oldHead = c.SectionHead(section - 1)
  288. }
  289. // Process the newly defined section in the background
  290. c.lock.Unlock()
  291. newHead, err := c.processSection(section, oldHead)
  292. if err != nil {
  293. select {
  294. case <-c.ctx.Done():
  295. <-c.quit <- nil
  296. return
  297. default:
  298. }
  299. c.log.Error("Section processing failed", "error", err)
  300. }
  301. c.lock.Lock()
  302. // If processing succeeded and no reorgs occcurred, mark the section completed
  303. if err == nil && oldHead == c.SectionHead(section-1) {
  304. c.setSectionHead(section, newHead)
  305. c.setValidSections(section + 1)
  306. if c.storedSections == c.knownSections && updating {
  307. updating = false
  308. c.log.Info("Finished upgrading chain index")
  309. }
  310. c.cascadedHead = c.storedSections*c.sectionSize - 1
  311. for _, child := range c.children {
  312. c.log.Trace("Cascading chain index update", "head", c.cascadedHead)
  313. child.newHead(c.cascadedHead, false)
  314. }
  315. } else {
  316. // If processing failed, don't retry until further notification
  317. c.log.Debug("Chain index processing failed", "section", section, "err", err)
  318. c.knownSections = c.storedSections
  319. }
  320. }
  321. // If there are still further sections to process, reschedule
  322. if c.knownSections > c.storedSections {
  323. time.AfterFunc(c.throttling, func() {
  324. select {
  325. case c.update <- struct{}{}:
  326. default:
  327. }
  328. })
  329. }
  330. c.lock.Unlock()
  331. }
  332. }
  333. }
  334. // processSection processes an entire section by calling backend functions while
  335. // ensuring the continuity of the passed headers. Since the chain mutex is not
  336. // held while processing, the continuity can be broken by a long reorg, in which
  337. // case the function returns with an error.
  338. func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (common.Hash, error) {
  339. c.log.Trace("Processing new chain section", "section", section)
  340. // Reset and partial processing
  341. if err := c.backend.Reset(c.ctx, section, lastHead); err != nil {
  342. c.setValidSections(0)
  343. return common.Hash{}, err
  344. }
  345. for number := section * c.sectionSize; number < (section+1)*c.sectionSize; number++ {
  346. hash := rawdb.ReadCanonicalHash(c.chainDb, number)
  347. if hash == (common.Hash{}) {
  348. return common.Hash{}, fmt.Errorf("canonical block #%d unknown", number)
  349. }
  350. header := rawdb.ReadHeader(c.chainDb, hash, number)
  351. if header == nil {
  352. return common.Hash{}, fmt.Errorf("block #%d [%x…] not found", number, hash[:4])
  353. } else if header.ParentHash != lastHead {
  354. return common.Hash{}, fmt.Errorf("chain reorged during section processing")
  355. }
  356. if err := c.backend.Process(c.ctx, header); err != nil {
  357. return common.Hash{}, err
  358. }
  359. lastHead = header.Hash()
  360. }
  361. if err := c.backend.Commit(); err != nil {
  362. return common.Hash{}, err
  363. }
  364. return lastHead, nil
  365. }
  366. // Sections returns the number of processed sections maintained by the indexer
  367. // and also the information about the last header indexed for potential canonical
  368. // verifications.
  369. func (c *ChainIndexer) Sections() (uint64, uint64, common.Hash) {
  370. c.lock.Lock()
  371. defer c.lock.Unlock()
  372. return c.storedSections, c.storedSections*c.sectionSize - 1, c.SectionHead(c.storedSections - 1)
  373. }
  374. // AddChildIndexer adds a child ChainIndexer that can use the output of this one
  375. func (c *ChainIndexer) AddChildIndexer(indexer *ChainIndexer) {
  376. c.lock.Lock()
  377. defer c.lock.Unlock()
  378. c.children = append(c.children, indexer)
  379. // Cascade any pending updates to new children too
  380. sections := c.storedSections
  381. if c.knownSections < sections {
  382. // if a section is "stored" but not "known" then it is a checkpoint without
  383. // available chain data so we should not cascade it yet
  384. sections = c.knownSections
  385. }
  386. if sections > 0 {
  387. indexer.newHead(sections*c.sectionSize-1, false)
  388. }
  389. }
  390. // loadValidSections reads the number of valid sections from the index database
  391. // and caches is into the local state.
  392. func (c *ChainIndexer) loadValidSections() {
  393. data, _ := c.indexDb.Get([]byte("count"))
  394. if len(data) == 8 {
  395. c.storedSections = binary.BigEndian.Uint64(data)
  396. }
  397. }
  398. // setValidSections writes the number of valid sections to the index database
  399. func (c *ChainIndexer) setValidSections(sections uint64) {
  400. // Set the current number of valid sections in the database
  401. var data [8]byte
  402. binary.BigEndian.PutUint64(data[:], sections)
  403. c.indexDb.Put([]byte("count"), data[:])
  404. // Remove any reorged sections, caching the valids in the mean time
  405. for c.storedSections > sections {
  406. c.storedSections--
  407. c.removeSectionHead(c.storedSections)
  408. }
  409. c.storedSections = sections // needed if new > old
  410. }
  411. // SectionHead retrieves the last block hash of a processed section from the
  412. // index database.
  413. func (c *ChainIndexer) SectionHead(section uint64) common.Hash {
  414. var data [8]byte
  415. binary.BigEndian.PutUint64(data[:], section)
  416. hash, _ := c.indexDb.Get(append([]byte("shead"), data[:]...))
  417. if len(hash) == len(common.Hash{}) {
  418. return common.BytesToHash(hash)
  419. }
  420. return common.Hash{}
  421. }
  422. // setSectionHead writes the last block hash of a processed section to the index
  423. // database.
  424. func (c *ChainIndexer) setSectionHead(section uint64, hash common.Hash) {
  425. var data [8]byte
  426. binary.BigEndian.PutUint64(data[:], section)
  427. c.indexDb.Put(append([]byte("shead"), data[:]...), hash.Bytes())
  428. }
  429. // removeSectionHead removes the reference to a processed section from the index
  430. // database.
  431. func (c *ChainIndexer) removeSectionHead(section uint64) {
  432. var data [8]byte
  433. binary.BigEndian.PutUint64(data[:], section)
  434. c.indexDb.Delete(append([]byte("shead"), data[:]...))
  435. }