Skip to content

Commit 13bb575

Browse files
committed
core: cache chain head
1 parent 8777ba0 commit 13bb575

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

core/txindexer.go

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,10 @@ type txIndexer struct {
4747
// and all others shouldn't.
4848
limit uint64
4949

50+
// The current head of blockchain for transaction indexing. This field
51+
// is accessed by both the indexer and the indexing progress queries.
52+
head atomic.Uint64
53+
5054
// The current tail of the indexed transactions, null indicates
5155
// that no transactions have been indexed yet.
5256
//
@@ -74,6 +78,7 @@ func newTxIndexer(limit uint64, chain *BlockChain) *txIndexer {
7478
term: make(chan chan struct{}),
7579
closed: make(chan struct{}),
7680
}
81+
indexer.head.Store(indexer.resolveHead())
7782
indexer.tail.Store(rawdb.ReadTxIndexTail(chain.db))
7883

7984
go indexer.loop(chain)
@@ -228,16 +233,15 @@ func (indexer *txIndexer) loop(chain *BlockChain) {
228233

229234
// Listening to chain events and manipulate the transaction indexes.
230235
var (
231-
stop chan struct{} // Non-nil if background routine is active
232-
done chan struct{} // Non-nil if background routine is active
233-
head = indexer.resolveHead() // The latest announced chain head
234-
236+
stop chan struct{} // Non-nil if background routine is active
237+
done chan struct{} // Non-nil if background routine is active
235238
headCh = make(chan ChainHeadEvent)
236239
sub = chain.SubscribeChainHeadEvent(headCh)
237240
)
238241
defer sub.Unsubscribe()
239242

240243
// Validate the transaction indexes and repair if necessary
244+
head := indexer.head.Load()
241245
indexer.repair(head)
242246

243247
// Launch the initial processing if chain is not empty (head != genesis).
@@ -250,15 +254,18 @@ func (indexer *txIndexer) loop(chain *BlockChain) {
250254
for {
251255
select {
252256
case h := <-headCh:
257+
indexer.head.Store(h.Header.Number.Uint64())
253258
if done == nil {
254259
stop = make(chan struct{})
255260
done = make(chan struct{})
256261
go indexer.run(h.Header.Number.Uint64(), stop, done)
257262
}
263+
258264
case <-done:
259265
stop = nil
260266
done = nil
261267
indexer.tail.Store(rawdb.ReadTxIndexTail(indexer.db))
268+
262269
case ch := <-indexer.term:
263270
if stop != nil {
264271
close(stop)
@@ -314,7 +321,7 @@ func (indexer *txIndexer) report(head uint64, tail *uint64) TxIndexProgress {
314321
// only updated at the end of each indexing operation. However, this delay is
315322
// considered acceptable.
316323
func (indexer *txIndexer) txIndexProgress() TxIndexProgress {
317-
return indexer.report(indexer.resolveHead(), indexer.tail.Load())
324+
return indexer.report(indexer.head.Load(), indexer.tail.Load())
318325
}
319326

320327
// close shutdown the indexer. Safe to be called for multiple times.

0 commit comments

Comments
 (0)