chain_indexer.go 15 KB

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