Skip to content

Commit d55e136

Browse files
fjlshekhirin
authored andcommitted
all: remove remaining uses of untyped golang-lru (ethereum#26194)
1 parent fdb8cde commit d55e136

File tree

8 files changed

+66
-68
lines changed

8 files changed

+66
-68
lines changed

common/lru/basiclru.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ type cacheItem[K any, V any] struct {
3434

3535
// NewBasicLRU creates a new LRU cache.
3636
func NewBasicLRU[K comparable, V any](capacity int) BasicLRU[K, V] {
37-
if capacity < 0 {
37+
if capacity <= 0 {
3838
capacity = 1
3939
}
4040
c := BasicLRU[K, V]{

consensus/clique/clique.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import (
3030
"github.com/ethereum/go-ethereum/accounts"
3131
"github.com/ethereum/go-ethereum/common"
3232
"github.com/ethereum/go-ethereum/common/hexutil"
33+
lru "github.com/ethereum/go-ethereum/common/lru"
3334
"github.com/ethereum/go-ethereum/consensus"
3435
"github.com/ethereum/go-ethereum/consensus/misc"
3536
"github.com/ethereum/go-ethereum/core/state"
@@ -41,7 +42,6 @@ import (
4142
"github.com/ethereum/go-ethereum/rlp"
4243
"github.com/ethereum/go-ethereum/rpc"
4344
"github.com/ethereum/go-ethereum/trie"
44-
lru "github.com/hashicorp/golang-lru"
4545
"golang.org/x/crypto/sha3"
4646
)
4747

@@ -143,11 +143,11 @@ var (
143143
type SignerFn func(signer accounts.Account, mimeType string, message []byte) ([]byte, error)
144144

145145
// ecrecover extracts the Ethereum account address from a signed header.
146-
func ecrecover(header *types.Header, sigcache *lru.ARCCache) (common.Address, error) {
146+
func ecrecover(header *types.Header, sigcache *sigLRU) (common.Address, error) {
147147
// If the signature's already cached, return that
148148
hash := header.Hash()
149149
if address, known := sigcache.Get(hash); known {
150-
return address.(common.Address), nil
150+
return address, nil
151151
}
152152
// Retrieve the signature from the header extra-data
153153
if len(header.Extra) < extraSeal {
@@ -173,8 +173,8 @@ type Clique struct {
173173
config *params.CliqueConfig // Consensus engine configuration parameters
174174
db ethdb.Database // Database to store and retrieve snapshot checkpoints
175175

176-
recents *lru.ARCCache // Snapshots for recent block to speed up reorgs
177-
signatures *lru.ARCCache // Signatures of recent blocks to speed up mining
176+
recents *lru.Cache[common.Hash, *Snapshot] // Snapshots for recent block to speed up reorgs
177+
signatures *sigLRU // Signatures of recent blocks to speed up mining
178178

179179
proposals map[common.Address]bool // Current list of proposals we are pushing
180180

@@ -195,8 +195,8 @@ func New(config *params.CliqueConfig, db ethdb.Database) *Clique {
195195
conf.Epoch = epochLength
196196
}
197197
// Allocate the snapshot caches and create the engine
198-
recents, _ := lru.NewARC(inmemorySnapshots)
199-
signatures, _ := lru.NewARC(inmemorySignatures)
198+
recents := lru.NewCache[common.Hash, *Snapshot](inmemorySnapshots)
199+
signatures := lru.NewCache[common.Hash, common.Address](inmemorySignatures)
200200

201201
return &Clique{
202202
config: &conf,
@@ -375,7 +375,7 @@ func (c *Clique) snapshot(chain consensus.ChainHeaderReader, number uint64, hash
375375
for snap == nil {
376376
// If an in-memory snapshot was found, use that
377377
if s, ok := c.recents.Get(hash); ok {
378-
snap = s.(*Snapshot)
378+
snap = s
379379
break
380380
}
381381
// If an on-disk checkpoint snapshot can be found, use that

consensus/clique/snapshot.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,12 @@ import (
2323
"time"
2424

2525
"github.com/ethereum/go-ethereum/common"
26+
"github.com/ethereum/go-ethereum/common/lru"
2627
"github.com/ethereum/go-ethereum/core/rawdb"
2728
"github.com/ethereum/go-ethereum/core/types"
2829
"github.com/ethereum/go-ethereum/ethdb"
2930
"github.com/ethereum/go-ethereum/log"
3031
"github.com/ethereum/go-ethereum/params"
31-
lru "github.com/hashicorp/golang-lru"
3232
)
3333

3434
// Vote represents a single vote that an authorized signer made to modify the
@@ -47,10 +47,12 @@ type Tally struct {
4747
Votes int `json:"votes"` // Number of votes until now wanting to pass the proposal
4848
}
4949

50+
type sigLRU = lru.Cache[common.Hash, common.Address]
51+
5052
// Snapshot is the state of the authorization voting at a given point in time.
5153
type Snapshot struct {
5254
config *params.CliqueConfig // Consensus engine parameters to fine tune behavior
53-
sigcache *lru.ARCCache // Cache of recent block signatures to speed up ecrecover
55+
sigcache *sigLRU // Cache of recent block signatures to speed up ecrecover
5456

5557
Number uint64 `json:"number"` // Block number where the snapshot was created
5658
Hash common.Hash `json:"hash"` // Block hash where the snapshot was created
@@ -70,7 +72,7 @@ func (s signersAscending) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
7072
// newSnapshot creates a new snapshot with the specified startup parameters. This
7173
// method does not initialize the set of recent signers, so only ever use if for
7274
// the genesis block.
73-
func newSnapshot(config *params.CliqueConfig, sigcache *lru.ARCCache, number uint64, hash common.Hash, signers []common.Address) *Snapshot {
75+
func newSnapshot(config *params.CliqueConfig, sigcache *sigLRU, number uint64, hash common.Hash, signers []common.Address) *Snapshot {
7476
snap := &Snapshot{
7577
config: config,
7678
sigcache: sigcache,
@@ -87,7 +89,7 @@ func newSnapshot(config *params.CliqueConfig, sigcache *lru.ARCCache, number uin
8789
}
8890

8991
// loadSnapshot loads an existing snapshot from the database.
90-
func loadSnapshot(config *params.CliqueConfig, sigcache *lru.ARCCache, db ethdb.Database, hash common.Hash) (*Snapshot, error) {
92+
func loadSnapshot(config *params.CliqueConfig, sigcache *sigLRU, db ethdb.Database, hash common.Hash) (*Snapshot, error) {
9193
blob, err := db.Get(append(rawdb.CliqueSnapshotPrefix, hash[:]...))
9294
if err != nil {
9395
return nil, err

consensus/ethash/ethash.go

Lines changed: 36 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,11 @@ import (
3434
"unsafe"
3535

3636
"github.com/edsrzf/mmap-go"
37+
lrupkg "github.com/ethereum/go-ethereum/common/lru"
3738
"github.com/ethereum/go-ethereum/consensus"
3839
"github.com/ethereum/go-ethereum/log"
3940
"github.com/ethereum/go-ethereum/metrics"
4041
"github.com/ethereum/go-ethereum/rpc"
41-
"github.com/hashicorp/golang-lru/simplelru"
4242
)
4343

4444
var ErrInvalidDumpMagic = errors.New("invalid dump magic")
@@ -165,34 +165,45 @@ func memoryMapAndGenerate(path string, size uint64, lock bool, generator func(bu
165165
return memoryMap(path, lock)
166166
}
167167

168+
type cacheOrDataset interface {
169+
*cache | *dataset
170+
}
171+
168172
// lru tracks caches or datasets by their last use time, keeping at most N of them.
169-
type lru struct {
173+
type lru[T cacheOrDataset] struct {
170174
what string
171-
new func(epoch uint64) interface{}
175+
new func(epoch uint64) T
172176
mu sync.Mutex
173177
// Items are kept in a LRU cache, but there is a special case:
174178
// We always keep an item for (highest seen epoch) + 1 as the 'future item'.
175-
cache *simplelru.LRU
179+
cache lrupkg.BasicLRU[uint64, T]
176180
future uint64
177-
futureItem interface{}
181+
futureItem T
178182
}
179183

180184
// newlru create a new least-recently-used cache for either the verification caches
181185
// or the mining datasets.
182-
func newlru(what string, maxItems int, new func(epoch uint64) interface{}) *lru {
183-
if maxItems <= 0 {
184-
maxItems = 1
186+
func newlru[T cacheOrDataset](maxItems int, new func(epoch uint64) T) *lru[T] {
187+
var what string
188+
switch any(T(nil)).(type) {
189+
case *cache:
190+
what = "cache"
191+
case *dataset:
192+
what = "dataset"
193+
default:
194+
panic("unknown type")
195+
}
196+
return &lru[T]{
197+
what: what,
198+
new: new,
199+
cache: lrupkg.NewBasicLRU[uint64, T](maxItems),
185200
}
186-
cache, _ := simplelru.NewLRU(maxItems, func(key, value interface{}) {
187-
log.Trace("Evicted ethash "+what, "epoch", key)
188-
})
189-
return &lru{what: what, new: new, cache: cache}
190201
}
191202

192203
// get retrieves or creates an item for the given epoch. The first return value is always
193204
// non-nil. The second return value is non-nil if lru thinks that an item will be useful in
194205
// the near future.
195-
func (lru *lru) get(epoch uint64) (item, future interface{}) {
206+
func (lru *lru[T]) get(epoch uint64) (item, future T) {
196207
lru.mu.Lock()
197208
defer lru.mu.Unlock()
198209

@@ -226,9 +237,8 @@ type cache struct {
226237
once sync.Once // Ensures the cache is generated only once
227238
}
228239

229-
// newCache creates a new ethash verification cache and returns it as a plain Go
230-
// interface to be usable in an LRU cache.
231-
func newCache(epoch uint64) interface{} {
240+
// newCache creates a new ethash verification cache.
241+
func newCache(epoch uint64) *cache {
232242
return &cache{epoch: epoch}
233243
}
234244

@@ -308,7 +318,7 @@ type dataset struct {
308318

309319
// newDataset creates a new ethash mining dataset and returns it as a plain Go
310320
// interface to be usable in an LRU cache.
311-
func newDataset(epoch uint64) interface{} {
321+
func newDataset(epoch uint64) *dataset {
312322
return &dataset{epoch: epoch}
313323
}
314324

@@ -439,8 +449,8 @@ type Config struct {
439449
type Ethash struct {
440450
config Config
441451

442-
caches *lru // In memory caches to avoid regenerating too often
443-
datasets *lru // In memory datasets to avoid regenerating too often
452+
caches *lru[*cache] // In memory caches to avoid regenerating too often
453+
datasets *lru[*dataset] // In memory datasets to avoid regenerating too often
444454

445455
// Mining related fields
446456
rand *rand.Rand // Properly seeded random source for nonces
@@ -477,8 +487,8 @@ func New(config Config, notify []string, noverify bool) *Ethash {
477487
}
478488
ethash := &Ethash{
479489
config: config,
480-
caches: newlru("cache", config.CachesInMem, newCache),
481-
datasets: newlru("dataset", config.DatasetsInMem, newDataset),
490+
caches: newlru(config.CachesInMem, newCache),
491+
datasets: newlru(config.DatasetsInMem, newDataset),
482492
update: make(chan struct{}),
483493
hashrate: metrics.NewMeterForced(),
484494
}
@@ -573,15 +583,13 @@ func (ethash *Ethash) StopRemoteSealer() error {
573583
// stored on disk, and finally generating one if none can be found.
574584
func (ethash *Ethash) cache(block uint64) *cache {
575585
epoch := block / epochLength
576-
currentI, futureI := ethash.caches.get(epoch)
577-
current := currentI.(*cache)
586+
current, future := ethash.caches.get(epoch)
578587

579588
// Wait for generation finish.
580589
current.generate(ethash.config.CacheDir, ethash.config.CachesOnDisk, ethash.config.CachesLockMmap, ethash.config.PowMode == ModeTest)
581590

582591
// If we need a new future cache, now's a good time to regenerate it.
583-
if futureI != nil {
584-
future := futureI.(*cache)
592+
if future != nil {
585593
go future.generate(ethash.config.CacheDir, ethash.config.CachesOnDisk, ethash.config.CachesLockMmap, ethash.config.PowMode == ModeTest)
586594
}
587595
return current
@@ -596,25 +604,20 @@ func (ethash *Ethash) cache(block uint64) *cache {
596604
func (ethash *Ethash) dataset(block uint64, async bool) *dataset {
597605
// Retrieve the requested ethash dataset
598606
epoch := block / epochLength
599-
currentI, futureI := ethash.datasets.get(epoch)
600-
current := currentI.(*dataset)
607+
current, future := ethash.datasets.get(epoch)
601608

602609
// If async is specified, generate everything in a background thread
603610
if async && !current.generated() {
604611
go func() {
605612
current.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ModeTest)
606-
607-
if futureI != nil {
608-
future := futureI.(*dataset)
613+
if future != nil {
609614
future.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ModeTest)
610615
}
611616
}()
612617
} else {
613618
// Either blocking generation was requested, or already done
614619
current.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ModeTest)
615-
616-
if futureI != nil {
617-
future := futureI.(*dataset)
620+
if future != nil {
618621
go future.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ModeTest)
619622
}
620623
}

go.mod

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ require (
3333
github.com/gorilla/websocket v1.4.2
3434
github.com/graph-gophers/graphql-go v1.3.0
3535
github.com/hashicorp/go-bexpr v0.1.10
36-
github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d
3736
github.com/holiman/big v0.0.0-20221017200358-a027dc42d04e
3837
github.com/holiman/bloomfilter/v2 v2.0.3
3938
github.com/holiman/uint256 v1.2.0

go.sum

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,6 @@ github.com/hashicorp/go-bexpr v0.1.10 h1:9kuI5PFotCboP3dkDYFr/wi0gg0QVbSNz5oFRpx
226226
github.com/hashicorp/go-bexpr v0.1.10/go.mod h1:oxlubA2vC/gFVfX1A6JGp7ls7uCDlfJn732ehYYg+g0=
227227
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
228228
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
229-
github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d h1:dg1dEPuWpEqDnvIw251EVy4zlP8gWbsGj4BsUKCRpYs=
230229
github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4=
231230
github.com/holiman/big v0.0.0-20221017200358-a027dc42d04e h1:pIYdhNkDh+YENVNi3gto8n9hAmRxKxoar0iE6BLucjw=
232231
github.com/holiman/big v0.0.0-20221017200358-a027dc42d04e/go.mod h1:j9cQbcqHQujT0oKJ38PylVfqohClLr3CvDC+Qcg+lhU=

les/vflux/server/clientdb.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,13 @@ import (
2222
"time"
2323

2424
"github.com/ethereum/go-ethereum/common"
25+
"github.com/ethereum/go-ethereum/common/lru"
2526
"github.com/ethereum/go-ethereum/common/mclock"
2627
"github.com/ethereum/go-ethereum/ethdb"
2728
"github.com/ethereum/go-ethereum/les/utils"
2829
"github.com/ethereum/go-ethereum/log"
2930
"github.com/ethereum/go-ethereum/p2p/enode"
3031
"github.com/ethereum/go-ethereum/rlp"
31-
lru "github.com/hashicorp/golang-lru"
3232
)
3333

3434
const (
@@ -57,7 +57,7 @@ var (
5757

5858
type nodeDB struct {
5959
db ethdb.KeyValueStore
60-
cache *lru.Cache
60+
cache *lru.Cache[string, utils.ExpiredValue]
6161
auxbuf []byte // 37-byte auxiliary buffer for key encoding
6262
verbuf [2]byte // 2-byte auxiliary buffer for db version
6363
evictCallBack func(mclock.AbsTime, bool, utils.ExpiredValue) bool // Callback to determine whether the balance can be evicted.
@@ -67,10 +67,9 @@ type nodeDB struct {
6767
}
6868

6969
func newNodeDB(db ethdb.KeyValueStore, clock mclock.Clock) *nodeDB {
70-
cache, _ := lru.New(balanceCacheLimit)
7170
ndb := &nodeDB{
7271
db: db,
73-
cache: cache,
72+
cache: lru.NewCache[string, utils.ExpiredValue](balanceCacheLimit),
7473
auxbuf: make([]byte, 37),
7574
clock: clock,
7675
closeCh: make(chan struct{}),
@@ -125,8 +124,9 @@ func (db *nodeDB) getOrNewBalance(id []byte, neg bool) utils.ExpiredValue {
125124
key := db.key(id, neg)
126125
item, exist := db.cache.Get(string(key))
127126
if exist {
128-
return item.(utils.ExpiredValue)
127+
return item
129128
}
129+
130130
var b utils.ExpiredValue
131131
enc, err := db.db.Get(key)
132132
if err != nil || len(enc) == 0 {

0 commit comments

Comments
 (0)