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