chain_indexer.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. if h := FindCommonAncestor(c.chainDb, prevHeader, header); h != nil {
  178. c.newHead(h.Number.Uint64(), true)
  179. }
  180. }
  181. c.newHead(header.Number.Uint64(), false)
  182. prevHeader, prevHash = header, header.Hash()
  183. }
  184. }
  185. }
  186. // newHead notifies the indexer about new chain heads and/or reorgs.
  187. func (c *ChainIndexer) newHead(head uint64, reorg bool) {
  188. c.lock.Lock()
  189. defer c.lock.Unlock()
  190. // If a reorg happened, invalidate all sections until that point
  191. if reorg {
  192. // Revert the known section number to the reorg point
  193. changed := head / c.sectionSize
  194. if changed < c.knownSections {
  195. c.knownSections = changed
  196. }
  197. // Revert the stored sections from the database to the reorg point
  198. if changed < c.storedSections {
  199. c.setValidSections(changed)
  200. }
  201. // Update the new head number to the finalized section end and notify children
  202. head = changed * c.sectionSize
  203. if head < c.cascadedHead {
  204. c.cascadedHead = head
  205. for _, child := range c.children {
  206. child.newHead(c.cascadedHead, true)
  207. }
  208. }
  209. return
  210. }
  211. // No reorg, calculate the number of newly known sections and update if high enough
  212. var sections uint64
  213. if head >= c.confirmsReq {
  214. sections = (head + 1 - c.confirmsReq) / c.sectionSize
  215. if sections > c.knownSections {
  216. c.knownSections = sections
  217. select {
  218. case c.update <- struct{}{}:
  219. default:
  220. }
  221. }
  222. }
  223. }
  224. // updateLoop is the main event loop of the indexer which pushes chain segments
  225. // down into the processing backend.
  226. func (c *ChainIndexer) updateLoop() {
  227. var (
  228. updating bool
  229. updated time.Time
  230. )
  231. for {
  232. select {
  233. case errc := <-c.quit:
  234. // Chain indexer terminating, report no failure and abort
  235. errc <- nil
  236. return
  237. case <-c.update:
  238. // Section headers completed (or rolled back), update the index
  239. c.lock.Lock()
  240. if c.knownSections > c.storedSections {
  241. // Periodically print an upgrade log message to the user
  242. if time.Since(updated) > 8*time.Second {
  243. if c.knownSections > c.storedSections+1 {
  244. updating = true
  245. c.log.Info("Upgrading chain index", "percentage", c.storedSections*100/c.knownSections)
  246. }
  247. updated = time.Now()
  248. }
  249. // Cache the current section count and head to allow unlocking the mutex
  250. section := c.storedSections
  251. var oldHead common.Hash
  252. if section > 0 {
  253. oldHead = c.SectionHead(section - 1)
  254. }
  255. // Process the newly defined section in the background
  256. c.lock.Unlock()
  257. newHead, err := c.processSection(section, oldHead)
  258. if err != nil {
  259. c.log.Error("Section processing failed", "error", err)
  260. }
  261. c.lock.Lock()
  262. // If processing succeeded and no reorgs occcurred, mark the section completed
  263. if err == nil && oldHead == c.SectionHead(section-1) {
  264. c.setSectionHead(section, newHead)
  265. c.setValidSections(section + 1)
  266. if c.storedSections == c.knownSections && updating {
  267. updating = false
  268. c.log.Info("Finished upgrading chain index")
  269. }
  270. c.cascadedHead = c.storedSections*c.sectionSize - 1
  271. for _, child := range c.children {
  272. c.log.Trace("Cascading chain index update", "head", c.cascadedHead)
  273. child.newHead(c.cascadedHead, false)
  274. }
  275. } else {
  276. // If processing failed, don't retry until further notification
  277. c.log.Debug("Chain index processing failed", "section", section, "err", err)
  278. c.knownSections = c.storedSections
  279. }
  280. }
  281. // If there are still further sections to process, reschedule
  282. if c.knownSections > c.storedSections {
  283. time.AfterFunc(c.throttling, func() {
  284. select {
  285. case c.update <- struct{}{}:
  286. default:
  287. }
  288. })
  289. }
  290. c.lock.Unlock()
  291. }
  292. }
  293. }
  294. // processSection processes an entire section by calling backend functions while
  295. // ensuring the continuity of the passed headers. Since the chain mutex is not
  296. // held while processing, the continuity can be broken by a long reorg, in which
  297. // case the function returns with an error.
  298. func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (common.Hash, error) {
  299. c.log.Trace("Processing new chain section", "section", section)
  300. // Reset and partial processing
  301. if err := c.backend.Reset(section, lastHead); err != nil {
  302. c.setValidSections(0)
  303. return common.Hash{}, err
  304. }
  305. for number := section * c.sectionSize; number < (section+1)*c.sectionSize; number++ {
  306. hash := GetCanonicalHash(c.chainDb, number)
  307. if hash == (common.Hash{}) {
  308. return common.Hash{}, fmt.Errorf("canonical block #%d unknown", number)
  309. }
  310. header := GetHeader(c.chainDb, hash, number)
  311. if header == nil {
  312. return common.Hash{}, fmt.Errorf("block #%d [%x…] not found", number, hash[:4])
  313. } else if header.ParentHash != lastHead {
  314. return common.Hash{}, fmt.Errorf("chain reorged during section processing")
  315. }
  316. c.backend.Process(header)
  317. lastHead = header.Hash()
  318. }
  319. if err := c.backend.Commit(); err != nil {
  320. c.log.Error("Section commit failed", "error", err)
  321. return common.Hash{}, err
  322. }
  323. return lastHead, nil
  324. }
  325. // Sections returns the number of processed sections maintained by the indexer
  326. // and also the information about the last header indexed for potential canonical
  327. // verifications.
  328. func (c *ChainIndexer) Sections() (uint64, uint64, common.Hash) {
  329. c.lock.Lock()
  330. defer c.lock.Unlock()
  331. return c.storedSections, c.storedSections*c.sectionSize - 1, c.SectionHead(c.storedSections - 1)
  332. }
  333. // AddChildIndexer adds a child ChainIndexer that can use the output of this one
  334. func (c *ChainIndexer) AddChildIndexer(indexer *ChainIndexer) {
  335. c.lock.Lock()
  336. defer c.lock.Unlock()
  337. c.children = append(c.children, indexer)
  338. // Cascade any pending updates to new children too
  339. if c.storedSections > 0 {
  340. indexer.newHead(c.storedSections*c.sectionSize-1, false)
  341. }
  342. }
  343. // loadValidSections reads the number of valid sections from the index database
  344. // and caches is into the local state.
  345. func (c *ChainIndexer) loadValidSections() {
  346. data, _ := c.indexDb.Get([]byte("count"))
  347. if len(data) == 8 {
  348. c.storedSections = binary.BigEndian.Uint64(data[:])
  349. }
  350. }
  351. // setValidSections writes the number of valid sections to the index database
  352. func (c *ChainIndexer) setValidSections(sections uint64) {
  353. // Set the current number of valid sections in the database
  354. var data [8]byte
  355. binary.BigEndian.PutUint64(data[:], sections)
  356. c.indexDb.Put([]byte("count"), data[:])
  357. // Remove any reorged sections, caching the valids in the mean time
  358. for c.storedSections > sections {
  359. c.storedSections--
  360. c.removeSectionHead(c.storedSections)
  361. }
  362. c.storedSections = sections // needed if new > old
  363. }
  364. // SectionHead retrieves the last block hash of a processed section from the
  365. // index database.
  366. func (c *ChainIndexer) SectionHead(section uint64) common.Hash {
  367. var data [8]byte
  368. binary.BigEndian.PutUint64(data[:], section)
  369. hash, _ := c.indexDb.Get(append([]byte("shead"), data[:]...))
  370. if len(hash) == len(common.Hash{}) {
  371. return common.BytesToHash(hash)
  372. }
  373. return common.Hash{}
  374. }
  375. // setSectionHead writes the last block hash of a processed section to the index
  376. // database.
  377. func (c *ChainIndexer) setSectionHead(section uint64, hash common.Hash) {
  378. var data [8]byte
  379. binary.BigEndian.PutUint64(data[:], section)
  380. c.indexDb.Put(append([]byte("shead"), data[:]...), hash.Bytes())
  381. }
  382. // removeSectionHead removes the reference to a processed section from the index
  383. // database.
  384. func (c *ChainIndexer) removeSectionHead(section uint64) {
  385. var data [8]byte
  386. binary.BigEndian.PutUint64(data[:], section)
  387. c.indexDb.Delete(append([]byte("shead"), data[:]...))
  388. }