chain_indexer.go 15 KB

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