Skip to content

Commit b684d5f

Browse files
committed
core: add lightweight HasCanonicalTransaction check
We only had the getter exposed, which is heavy compared to just checking the existence. Signed-off-by: Csaba Kiraly <[email protected]>
1 parent d9e8558 commit b684d5f

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

core/blockchain_reader.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,25 @@ func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, max
321321
return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
322322
}
323323

324+
// HasCanonicalTransaction is a lightweight check to see if a transaction is present
325+
// in the indexed part of the canonical chain without retrieving the transaction itself.
326+
// It's view is limited to the indexed part of the chain, so very old transactions
327+
// might fail the check if the indexer was constrained, or indexing is still in progress.
328+
func (bc *BlockChain) HasCanonicalTransaction(hash common.Hash) bool {
329+
bc.txLookupLock.RLock()
330+
defer bc.txLookupLock.RUnlock()
331+
332+
// Check in memory cache first
333+
if _, exist := bc.txLookupCache.Get(hash); exist {
334+
return true
335+
}
336+
// Fallback to database lookup, without reading the transaction itself
337+
if rawdb.HasCanonicalTransaction(bc.db, hash) {
338+
return true
339+
}
340+
return false
341+
}
342+
324343
// GetCanonicalTransaction retrieves the lookup along with the transaction
325344
// itself associate with the given transaction hash.
326345
//

core/rawdb/accessors_indexes.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,12 @@ func findTxInBlockBody(blockbody rlp.RawValue, target common.Hash) (*types.Trans
174174
return nil, 0, errors.New("transaction not found")
175175
}
176176

177+
// HasCanonicalTransaction checks whether a specific transaction is in the database.
178+
func HasCanonicalTransaction(db ethdb.Reader, hash common.Hash) bool {
179+
blockNumber := ReadTxLookupEntry(db, hash)
180+
return blockNumber != nil
181+
}
182+
177183
// ReadCanonicalTransaction retrieves a specific transaction from the database, along
178184
// with its added positional metadata. Notably, only the transaction in the canonical
179185
// chain is visible.

0 commit comments

Comments
 (0)