chain_indexer.go 15 KB

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