From 9ca7e0f4a3e724e68681e2385054c24f5af5239b Mon Sep 17 00:00:00 2001 From: yperbasis Date: Tue, 28 May 2024 22:06:25 +0200 Subject: [PATCH 1/3] use clear from go1.21 --- cl/cltypes/solid/uint64slice_byte.go | 8 ++------ crypto/crypto.go | 12 +++--------- crypto/signature_cgo.go | 2 +- p2p/discover/v5wire/crypto.go | 4 +--- rlp/decode.go | 4 +--- 5 files changed, 8 insertions(+), 22 deletions(-) diff --git a/cl/cltypes/solid/uint64slice_byte.go b/cl/cltypes/solid/uint64slice_byte.go index 8cdaa7fa7fe..3fd39423745 100644 --- a/cl/cltypes/solid/uint64slice_byte.go +++ b/cl/cltypes/solid/uint64slice_byte.go @@ -53,12 +53,8 @@ func NewUint64Slice(limit int) *byteBasedUint64Slice { // Clear clears the slice by setting its length to 0 and zeroing out its backing array. func (arr *byteBasedUint64Slice) Clear() { arr.l = 0 - for i := range arr.u { - arr.u[i] = 0 - } - for i := range arr.treeCacheBuffer { - arr.treeCacheBuffer[i] = 0 - } + clear(arr.u) + clear(arr.treeCacheBuffer) } // CopyTo copies the slice to a target slice. diff --git a/crypto/crypto.go b/crypto/crypto.go index 6d385075d92..799da160aa8 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -24,20 +24,20 @@ import ( "encoding/hex" "errors" "fmt" - "github.com/ledgerwatch/erigon-lib/common/hexutil" "hash" "io" "math/big" "os" "github.com/holiman/uint256" - libcommon "github.com/ledgerwatch/erigon-lib/common" "golang.org/x/crypto/sha3" - "github.com/ledgerwatch/erigon/crypto/cryptopool" + libcommon "github.com/ledgerwatch/erigon-lib/common" + "github.com/ledgerwatch/erigon-lib/common/hexutil" "github.com/ledgerwatch/erigon/common/math" "github.com/ledgerwatch/erigon/common/u256" + "github.com/ledgerwatch/erigon/crypto/cryptopool" "github.com/ledgerwatch/erigon/rlp" ) @@ -318,9 +318,3 @@ func PubkeyToAddress(p ecdsa.PublicKey) libcommon.Address { pubBytes := MarshalPubkey(&p) return libcommon.BytesToAddress(Keccak256(pubBytes)[12:]) } - -func zeroBytes(bytes []byte) { - for i := range bytes { - bytes[i] = 0 - } -} diff --git a/crypto/signature_cgo.go b/crypto/signature_cgo.go index 0ea11872ad2..8a76b65d19a 100644 --- a/crypto/signature_cgo.go +++ b/crypto/signature_cgo.go @@ -61,7 +61,7 @@ func Sign(digestHash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) { return nil, fmt.Errorf("hash is required to be exactly %d bytes (%d)", DigestLength, len(digestHash)) } seckey := math.PaddedBigBytes(prv.D, prv.Params().BitSize/8) - defer zeroBytes(seckey) + defer clear(seckey) return secp256k1.Sign(digestHash, seckey) } diff --git a/p2p/discover/v5wire/crypto.go b/p2p/discover/v5wire/crypto.go index bb3bbefa21a..e0588698481 100644 --- a/p2p/discover/v5wire/crypto.go +++ b/p2p/discover/v5wire/crypto.go @@ -129,9 +129,7 @@ func deriveKeys(hash hashFn, priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey, n1, n sec := session{writeKey: make([]byte, aesKeySize), readKey: make([]byte, aesKeySize)} kdf.Read(sec.writeKey) //nolint:errcheck kdf.Read(sec.readKey) //nolint:errcheck - for i := range eph { - eph[i] = 0 - } + clear(eph) return &sec } diff --git a/rlp/decode.go b/rlp/decode.go index 1c16d3fd3fe..a7cbc62f3b2 100644 --- a/rlp/decode.go +++ b/rlp/decode.go @@ -1063,9 +1063,7 @@ func (s *Stream) readUint(size byte) (uint64, error) { return uint64(b), err default: buffer := s.uintbuf[:8] - for i := range buffer { - buffer[i] = 0 - } + clear(buffer) start := int(8 - size) if err := s.readFull(buffer[start:]); err != nil { return 0, err From 502329daa5c2cf66009f841a1b79639575948100 Mon Sep 17 00:00:00 2001 From: yperbasis Date: Tue, 28 May 2024 22:31:03 +0200 Subject: [PATCH 2/3] replace cmp.Min/Max with built-ins --- cmd/integration/commands/refetence_db.go | 13 +++++++------ cmd/integration/commands/stages.go | 6 ++---- cmd/utils/flags.go | 3 +-- core/rawdb/accessors_chain.go | 6 ++---- erigon-lib/common/cmp/cmp.go | 14 -------------- .../downloader/downloadercfg/downloadercfg.go | 2 +- erigon-lib/mmap/total_memory.go | 5 ++--- erigon-lib/seg/compress_fuzz_test.go | 3 +-- erigon-lib/seg/decompress_fuzz_test.go | 3 +-- erigon-lib/seg/silkworm_seg_fuzz_test.go | 4 +--- erigon-lib/state/history.go | 5 ++--- erigon-lib/state/inverted_index.go | 12 +++++------- erigon-lib/state/merge.go | 18 ++++++++---------- erigon-lib/txpool/fetch.go | 13 ++++++------- erigon-lib/txpool/pool.go | 11 +++++------ eth/ethconfig/estimate/esitmated_ram.go | 13 ++++++------- eth/stagedsync/exec3.go | 2 +- eth/stagedsync/stage_execute.go | 12 ++++++------ eth/stagedsync/stage_senders.go | 15 +++++++-------- eth/stagedsync/stage_txlookup.go | 7 +++---- p2p/discover/v5_udp.go | 8 ++++---- polygon/heimdall/heimdall_test.go | 3 +-- polygon/p2p/fetcher_base.go | 3 +-- polygon/sync/block_downloader.go | 5 ++--- turbo/jsonrpc/otterscan_contract_creator.go | 8 ++++---- ...tterscan_transaction_by_sender_and_nonce.go | 8 ++++---- .../freezeblocks/block_snapshots.go | 10 +++++----- .../freezeblocks/caplin_snapshots.go | 6 +++--- turbo/trie/trie.go | 3 +-- 29 files changed, 92 insertions(+), 129 deletions(-) diff --git a/cmd/integration/commands/refetence_db.go b/cmd/integration/commands/refetence_db.go index 078b8481e55..3ce0dc3247f 100644 --- a/cmd/integration/commands/refetence_db.go +++ b/cmd/integration/commands/refetence_db.go @@ -11,17 +11,18 @@ import ( "sync/atomic" "time" + "github.com/ledgerwatch/log/v3" + "github.com/spf13/cobra" + "golang.org/x/sync/errgroup" + "golang.org/x/sync/semaphore" + common2 "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon-lib/kv/backup" mdbx2 "github.com/ledgerwatch/erigon-lib/kv/mdbx" + "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/turbo/debug" - "github.com/ledgerwatch/log/v3" - "github.com/spf13/cobra" - "golang.org/x/sync/errgroup" - "golang.org/x/sync/semaphore" ) var stateBuckets = []string{ @@ -262,7 +263,7 @@ func mdbxTopDup(ctx context.Context, chaindata string, bucket string, logger log var _max int for _, i := range cnt { - _max = cmp.Max(i, _max) + _max = max(i, _max) } for k, i := range cnt { if i > _max-10 { diff --git a/cmd/integration/commands/stages.go b/cmd/integration/commands/stages.go index fb62e664234..98f82dec0a6 100644 --- a/cmd/integration/commands/stages.go +++ b/cmd/integration/commands/stages.go @@ -17,14 +17,12 @@ import ( "github.com/ledgerwatch/log/v3" "github.com/ledgerwatch/secp256k1" "github.com/spf13/cobra" - "golang.org/x/sync/semaphore" - "golang.org/x/sync/errgroup" + "golang.org/x/sync/semaphore" chain2 "github.com/ledgerwatch/erigon-lib/chain" common2 "github.com/ledgerwatch/erigon-lib/common" libcommon "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/common/datadir" "github.com/ledgerwatch/erigon-lib/common/dbg" "github.com/ledgerwatch/erigon-lib/config3" @@ -866,7 +864,7 @@ func stageHeaders(db kv.RwDB, ctx context.Context, logger log.Logger) error { if unwind > progress { unwindTo = 1 // keep genesis } else { - unwindTo = uint64(cmp.Max(1, int(progress)-int(unwind))) + unwindTo = uint64(max(1, int(progress)-int(unwind))) } if err = stages.SaveStageProgress(tx, stages.Headers, unwindTo); err != nil { diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index ba5a8fc6f07..eef9bef0010 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -36,7 +36,6 @@ import ( "github.com/ledgerwatch/erigon-lib/chain/networkname" "github.com/ledgerwatch/erigon-lib/chain/snapcfg" libcommon "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/common/datadir" "github.com/ledgerwatch/erigon-lib/common/metrics" libkzg "github.com/ledgerwatch/erigon-lib/crypto/kzg" @@ -408,7 +407,7 @@ var ( DBReadConcurrencyFlag = cli.IntFlag{ Name: "db.read.concurrency", Usage: "Does limit amount of parallel db reads. Default: equal to GOMAXPROCS (or number of CPU)", - Value: cmp.Min(cmp.Max(10, runtime.GOMAXPROCS(-1)*64), 9_000), + Value: min(max(10, runtime.GOMAXPROCS(-1)*64), 9_000), } RpcAccessListFlag = cli.StringFlag{ Name: "rpc.accessList", diff --git a/core/rawdb/accessors_chain.go b/core/rawdb/accessors_chain.go index 53f8e169329..59e19b628ce 100644 --- a/core/rawdb/accessors_chain.go +++ b/core/rawdb/accessors_chain.go @@ -26,17 +26,15 @@ import ( "math/big" "time" - "github.com/ledgerwatch/erigon-lib/kv/dbutils" - "github.com/gballet/go-verkle" "github.com/ledgerwatch/log/v3" "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/common/dbg" "github.com/ledgerwatch/erigon-lib/common/hexutility" "github.com/ledgerwatch/erigon-lib/common/length" "github.com/ledgerwatch/erigon-lib/kv" + "github.com/ledgerwatch/erigon-lib/kv/dbutils" "github.com/ledgerwatch/erigon-lib/kv/rawdbv3" "github.com/ledgerwatch/erigon/core/types" @@ -1037,7 +1035,7 @@ func PruneBlocks(tx kv.RwTx, blockTo uint64, blocksDeleteLimit int) error { return err } blockFrom := binary.BigEndian.Uint64(firstK) - stopAtBlock := cmp.Min(blockTo, blockFrom+uint64(blocksDeleteLimit)) + stopAtBlock := min(blockTo, blockFrom+uint64(blocksDeleteLimit)) var b *types.BodyForStorage diff --git a/erigon-lib/common/cmp/cmp.go b/erigon-lib/common/cmp/cmp.go index 7e7334010a6..564869e16e7 100644 --- a/erigon-lib/common/cmp/cmp.go +++ b/erigon-lib/common/cmp/cmp.go @@ -31,20 +31,6 @@ func InRange[T constraints.Ordered](min, max, val T) T { return val } -func Min[T constraints.Ordered](a, b T) T { - if a <= b { - return a - } - return b -} - -func Max[T constraints.Ordered](a, b T) T { - if a >= b { - return a - } - return b -} - func Compare[T constraints.Ordered](a, b T) int { switch { case a < b: diff --git a/erigon-lib/downloader/downloadercfg/downloadercfg.go b/erigon-lib/downloader/downloadercfg/downloadercfg.go index 10f24cabe4d..d8d3bd31b20 100644 --- a/erigon-lib/downloader/downloadercfg/downloadercfg.go +++ b/erigon-lib/downloader/downloadercfg/downloadercfg.go @@ -65,7 +65,7 @@ func Default() *torrent.ClientConfig { // better don't increase because erigon periodically producing "new seedable files" - and adding them to downloader. // it must not impact chain tip sync - so, limit resources to minimum by default. // but when downloader is started as a separated process - rise it to max - //torrentConfig.PieceHashersPerTorrent = cmp.Max(1, runtime.NumCPU()-1) + //torrentConfig.PieceHashersPerTorrent = max(1, runtime.NumCPU()-1) torrentConfig.MinDialTimeout = 6 * time.Second //default: 3s torrentConfig.HandshakesTimeout = 8 * time.Second //default: 4s diff --git a/erigon-lib/mmap/total_memory.go b/erigon-lib/mmap/total_memory.go index 75a2f38d7d8..c27fd25f421 100644 --- a/erigon-lib/mmap/total_memory.go +++ b/erigon-lib/mmap/total_memory.go @@ -3,7 +3,6 @@ package mmap import ( "runtime/debug" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/pbnjay/memory" ) @@ -11,11 +10,11 @@ func TotalMemory() uint64 { mem := memory.TotalMemory() if cgroupsMemLimit, err := cgroupsMemoryLimit(); (err == nil) && (cgroupsMemLimit > 0) { - mem = cmp.Min(mem, cgroupsMemLimit) + mem = min(mem, cgroupsMemLimit) } if goMemLimit := debug.SetMemoryLimit(-1); goMemLimit > 0 { - mem = cmp.Min(mem, uint64(goMemLimit)) + mem = min(mem, uint64(goMemLimit)) } return mem diff --git a/erigon-lib/seg/compress_fuzz_test.go b/erigon-lib/seg/compress_fuzz_test.go index ee6eac0d7f7..d0f9d53fe0e 100644 --- a/erigon-lib/seg/compress_fuzz_test.go +++ b/erigon-lib/seg/compress_fuzz_test.go @@ -24,7 +24,6 @@ import ( "path/filepath" "testing" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/log/v3" ) @@ -43,7 +42,7 @@ func FuzzCompress(f *testing.F) { if pos[i] == 0 { continue } - next := cmp.Min(j+int(pos[i]*10), len(x)-1) + next := min(j+int(pos[i]*10), len(x)-1) bbb := x[j:next] a = append(a, bbb) j = next diff --git a/erigon-lib/seg/decompress_fuzz_test.go b/erigon-lib/seg/decompress_fuzz_test.go index 0f35f517f34..1bb4a526fe3 100644 --- a/erigon-lib/seg/decompress_fuzz_test.go +++ b/erigon-lib/seg/decompress_fuzz_test.go @@ -8,7 +8,6 @@ import ( "path/filepath" "testing" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/log/v3" ) @@ -27,7 +26,7 @@ func FuzzDecompressMatch(f *testing.F) { if pos[i] == 0 { continue } - next := cmp.Min(j+int(pos[i]*10), len(x)-1) + next := min(j+int(pos[i]*10), len(x)-1) bbb := x[j:next] a = append(a, bbb) j = next diff --git a/erigon-lib/seg/silkworm_seg_fuzz_test.go b/erigon-lib/seg/silkworm_seg_fuzz_test.go index cf38cd22867..fa225bf3248 100644 --- a/erigon-lib/seg/silkworm_seg_fuzz_test.go +++ b/erigon-lib/seg/silkworm_seg_fuzz_test.go @@ -15,8 +15,6 @@ import ( "github.com/ledgerwatch/log/v3" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/ledgerwatch/erigon-lib/common/cmp" ) func makeSegFilePath(path string, suffix string) string { @@ -103,7 +101,7 @@ func NewRandPattern(r *rand.Rand, patternLen int) RandPattern { } func (p RandPattern) CopyTo(word []byte, offset int) { - copy(word[offset:cmp.Min(offset+len(p.pattern), len(word))], p.pattern) + copy(word[offset:min(offset+len(p.pattern), len(word))], p.pattern) } func generatePatterns(r *rand.Rand) []RandPattern { diff --git a/erigon-lib/state/history.go b/erigon-lib/state/history.go index 603f293d4c0..bb194ce3fac 100644 --- a/erigon-lib/state/history.go +++ b/erigon-lib/state/history.go @@ -29,7 +29,6 @@ import ( "strconv" "time" - "github.com/ledgerwatch/erigon-lib/kv/backup" btree2 "github.com/tidwall/btree" "golang.org/x/sync/errgroup" @@ -37,10 +36,10 @@ import ( "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/common/background" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/common/dir" "github.com/ledgerwatch/erigon-lib/etl" "github.com/ledgerwatch/erigon-lib/kv" + "github.com/ledgerwatch/erigon-lib/kv/backup" "github.com/ledgerwatch/erigon-lib/kv/bitmapdb" "github.com/ledgerwatch/erigon-lib/kv/iter" "github.com/ledgerwatch/erigon-lib/kv/order" @@ -1598,7 +1597,7 @@ func (ht *HistoryRoTx) iterateChangedFrozen(fromTxNum, toTxNum int, asc order.By hi := &HistoryChangesIterFiles{ hc: ht, - startTxNum: cmp.Max(0, uint64(fromTxNum)), + startTxNum: max(0, uint64(fromTxNum)), endTxNum: toTxNum, limit: limit, } diff --git a/erigon-lib/state/inverted_index.go b/erigon-lib/state/inverted_index.go index 7f164bca174..8d53d0596cf 100644 --- a/erigon-lib/state/inverted_index.go +++ b/erigon-lib/state/inverted_index.go @@ -33,28 +33,26 @@ import ( "sync" "time" - "github.com/ledgerwatch/erigon-lib/common/assert" - "github.com/RoaringBitmap/roaring/roaring64" - "github.com/ledgerwatch/erigon-lib/kv/backup" - "github.com/ledgerwatch/erigon-lib/seg" "github.com/ledgerwatch/log/v3" "github.com/spaolacci/murmur3" btree2 "github.com/tidwall/btree" "golang.org/x/sync/errgroup" + "github.com/ledgerwatch/erigon-lib/common/assert" "github.com/ledgerwatch/erigon-lib/common/background" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/common/datadir" "github.com/ledgerwatch/erigon-lib/common/dbg" "github.com/ledgerwatch/erigon-lib/common/dir" "github.com/ledgerwatch/erigon-lib/etl" "github.com/ledgerwatch/erigon-lib/kv" + "github.com/ledgerwatch/erigon-lib/kv/backup" "github.com/ledgerwatch/erigon-lib/kv/bitmapdb" "github.com/ledgerwatch/erigon-lib/kv/iter" "github.com/ledgerwatch/erigon-lib/kv/order" "github.com/ledgerwatch/erigon-lib/recsplit" "github.com/ledgerwatch/erigon-lib/recsplit/eliasfano32" + "github.com/ledgerwatch/erigon-lib/seg" ) type InvertedIndex struct { @@ -693,7 +691,7 @@ func (iit *InvertedIndexRoTx) smallestTxNum(tx kv.Tx) uint64 { fst, _ := kv.FirstKey(tx, iit.ii.indexKeysTable) if len(fst) > 0 { fstInDb := binary.BigEndian.Uint64(fst) - return cmp.Min(fstInDb, math.MaxUint64) + return min(fstInDb, math.MaxUint64) } return math.MaxUint64 } @@ -702,7 +700,7 @@ func (iit *InvertedIndexRoTx) highestTxNum(tx kv.Tx) uint64 { lst, _ := kv.LastKey(tx, iit.ii.indexKeysTable) if len(lst) > 0 { lstInDb := binary.BigEndian.Uint64(lst) - return cmp.Max(lstInDb, 0) + return max(lstInDb, 0) } return 0 } diff --git a/erigon-lib/state/merge.go b/erigon-lib/state/merge.go index 5868c367b90..2009746789c 100644 --- a/erigon-lib/state/merge.go +++ b/erigon-lib/state/merge.go @@ -27,14 +27,12 @@ import ( "path/filepath" "strings" - "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/log/v3" - "github.com/ledgerwatch/erigon-lib/common/background" - "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" + "github.com/ledgerwatch/erigon-lib/common/background" "github.com/ledgerwatch/erigon-lib/common/dir" + "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon-lib/recsplit" "github.com/ledgerwatch/erigon-lib/recsplit/eliasfano32" "github.com/ledgerwatch/erigon-lib/seg" @@ -68,7 +66,7 @@ func (ii *InvertedIndex) endIndexedTxNumMinimax(needFrozen bool) uint64 { if item.index == nil || (needFrozen && !item.frozen) { continue } - _max = cmp.Max(_max, item.endTxNum) + _max = max(_max, item.endTxNum) } return true }) @@ -98,11 +96,11 @@ func (h *History) endIndexedTxNumMinimax(needFrozen bool) uint64 { if item.index == nil || (needFrozen && !item.frozen) { continue } - _max = cmp.Max(_max, item.endTxNum) + _max = max(_max, item.endTxNum) } return true }) - return cmp.Min(_max, h.InvertedIndex.endIndexedTxNumMinimax(needFrozen)) + return min(_max, h.InvertedIndex.endIndexedTxNumMinimax(needFrozen)) } type DomainRanges struct { @@ -194,7 +192,7 @@ func (ht *HistoryRoTx) findMergeRange(maxEndTxNum, maxSpan uint64) HistoryRanges } endStep := item.endTxNum / ht.h.aggregationStep spanStep := endStep & -endStep // Extract rightmost bit in the binary representation of endStep, this corresponds to size of maximally possible merge ending at endStep - span := cmp.Min(spanStep*ht.h.aggregationStep, maxSpan) + span := min(spanStep*ht.h.aggregationStep, maxSpan) start := item.endTxNum - span foundSuperSet := r.indexStartTxNum == item.startTxNum && item.endTxNum >= r.historyEndTxNum if foundSuperSet { @@ -243,7 +241,7 @@ func (iit *InvertedIndexRoTx) findMergeRange(maxEndTxNum, maxSpan uint64) *Merge } endStep := item.endTxNum / iit.ii.aggregationStep spanStep := endStep & -endStep // Extract rightmost bit in the binary representation of endStep, this corresponds to size of maximally possible merge ending at endStep - span := cmp.Min(spanStep*iit.ii.aggregationStep, maxSpan) + span := min(spanStep*iit.ii.aggregationStep, maxSpan) start := item.endTxNum - span foundSuperSet := startTxNum == item.startTxNum && item.endTxNum >= endTxNum if foundSuperSet { @@ -328,7 +326,7 @@ func (ht *HistoryRoTx) maxTxNumInFiles(onlyFrozen bool) uint64 { } else { _max = ht.files[len(ht.files)-1].endTxNum } - return cmp.Min(_max, ht.iit.maxTxNumInFiles(onlyFrozen)) + return min(_max, ht.iit.maxTxNumInFiles(onlyFrozen)) } func (iit *InvertedIndexRoTx) maxTxNumInFiles(onlyFrozen bool) uint64 { diff --git a/erigon-lib/txpool/fetch.go b/erigon-lib/txpool/fetch.go index dd9a6f15e00..38e6107556a 100644 --- a/erigon-lib/txpool/fetch.go +++ b/erigon-lib/txpool/fetch.go @@ -23,9 +23,11 @@ import ( "sync" "time" - "github.com/ledgerwatch/erigon-lib/common/cmp" - "github.com/holiman/uint256" + "github.com/ledgerwatch/log/v3" + "google.golang.org/grpc" + "google.golang.org/protobuf/types/known/emptypb" + "github.com/ledgerwatch/erigon-lib/common/dbg" "github.com/ledgerwatch/erigon-lib/direct" "github.com/ledgerwatch/erigon-lib/gointerfaces/grpcutil" @@ -34,9 +36,6 @@ import ( "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon-lib/rlp" types2 "github.com/ledgerwatch/erigon-lib/types" - "github.com/ledgerwatch/log/v3" - "google.golang.org/grpc" - "google.golang.org/protobuf/types/known/emptypb" ) // Fetch connects to sentry and implements eth/66 protocol regarding the transaction @@ -285,7 +284,7 @@ func (f *Fetch) handleInboundMessage(ctx context.Context, req *sentry.InboundMes // limit to max 256 transactions in a reply const hashSize = 32 - hashes = hashes[:cmp.Min(len(hashes), 256*hashSize)] + hashes = hashes[:min(len(hashes), 256*hashSize)] var txs [][]byte responseSize := 0 @@ -298,7 +297,7 @@ func (f *Fetch) handleInboundMessage(ctx context.Context, req *sentry.InboundMes break } - txnHash := hashes[i:cmp.Min(i+hashSize, len(hashes))] + txnHash := hashes[i:min(i+hashSize, len(hashes))] txn, err := f.pool.GetRlp(tx, txnHash) if err != nil { return err diff --git a/erigon-lib/txpool/pool.go b/erigon-lib/txpool/pool.go index 1b4f38eb9e0..660c2c37cc0 100644 --- a/erigon-lib/txpool/pool.go +++ b/erigon-lib/txpool/pool.go @@ -39,10 +39,11 @@ import ( "github.com/google/btree" "github.com/hashicorp/golang-lru/v2/simplelru" "github.com/holiman/uint256" + "github.com/ledgerwatch/log/v3" + "github.com/ledgerwatch/erigon-lib/chain" "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/common/assert" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/common/dbg" "github.com/ledgerwatch/erigon-lib/common/fixedgas" "github.com/ledgerwatch/erigon-lib/common/u256" @@ -57,8 +58,6 @@ import ( "github.com/ledgerwatch/erigon-lib/metrics" "github.com/ledgerwatch/erigon-lib/txpool/txpoolcfg" "github.com/ledgerwatch/erigon-lib/types" - types2 "github.com/ledgerwatch/erigon-lib/types" - "github.com/ledgerwatch/log/v3" ) const DefaultBlockGasLimit = uint64(30000000) @@ -717,7 +716,7 @@ func (p *TxPool) best(n uint16, txs *types.TxsRlp, tx kv.Tx, onTopOf, availableG isShanghai := p.isShanghai() || p.isAgra() - txs.Resize(uint(cmp.Min(int(n), len(best.ms)))) + txs.Resize(uint(min(int(n), len(best.ms)))) var toRemove []*metaTx count := 0 i := 0 @@ -1630,7 +1629,7 @@ func (p *TxPool) onSenderStateChange(senderID uint64, senderNonce uint64, sender } mt.minFeeCap = *minFeeCap if mt.Tx.Tip.IsUint64() { - minTip = cmp.Min(minTip, mt.Tx.Tip.Uint64()) + minTip = min(minTip, mt.Tx.Tip.Uint64()) } mt.minTip = minTip @@ -1864,7 +1863,7 @@ func MainLoop(ctx context.Context, db kv.RwDB, p *TxPool, newTxs chan types.Anno continue } // Strip away blob wrapper, if applicable - slotRlp, err2 := types2.UnwrapTxPlayloadRlp(slotRlp) + slotRlp, err2 := types.UnwrapTxPlayloadRlp(slotRlp) if err2 != nil { continue } diff --git a/eth/ethconfig/estimate/esitmated_ram.go b/eth/ethconfig/estimate/esitmated_ram.go index 417d81b00a1..f4eca5d4606 100644 --- a/eth/ethconfig/estimate/esitmated_ram.go +++ b/eth/ethconfig/estimate/esitmated_ram.go @@ -5,7 +5,6 @@ import ( "github.com/c2h5oh/datasize" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/mmap" ) @@ -14,22 +13,22 @@ type EstimatedRamPerWorker datasize.ByteSize // Workers - return max workers amount based on total Memory/CPU's and estimated RAM per worker func (r EstimatedRamPerWorker) Workers() int { maxWorkersForGivenMemory := r.WorkersByRAMOnly() - res := cmp.Min(AlmostAllCPUs(), maxWorkersForGivenMemory) - return cmp.Max(1, res) // must have at-least 1 worker + res := min(AlmostAllCPUs(), maxWorkersForGivenMemory) + return max(1, res) // must have at-least 1 worker } func (r EstimatedRamPerWorker) WorkersHalf() int { - return cmp.Max(1, r.Workers()/2) + return max(1, r.Workers()/2) } func (r EstimatedRamPerWorker) WorkersQuarter() int { - return cmp.Max(1, r.Workers()/4) + return max(1, r.Workers()/4) } // WorkersByRAMOnly - return max workers amount based on total Memory and estimated RAM per worker func (r EstimatedRamPerWorker) WorkersByRAMOnly() int { // 50% of TotalMemory. Better don't count on 100% because OOM Killer may have aggressive defaults and other software may need RAM - return cmp.Max(1, int((mmap.TotalMemory()/2)/uint64(r))) + return max(1, int((mmap.TotalMemory()/2)/uint64(r))) } const ( @@ -49,5 +48,5 @@ const ( // AlmostAllCPUs - return all-but-one cpus. Leaving 1 cpu for "work producer", also cloud-providers do recommend leave 1 CPU for their IO software // user can reduce GOMAXPROCS env variable func AlmostAllCPUs() int { - return cmp.Max(1, runtime.GOMAXPROCS(-1)-1) + return max(1, runtime.GOMAXPROCS(-1)-1) } diff --git a/eth/stagedsync/exec3.go b/eth/stagedsync/exec3.go index ac478a3a342..4be00a86b18 100644 --- a/eth/stagedsync/exec3.go +++ b/eth/stagedsync/exec3.go @@ -1099,7 +1099,7 @@ func flushAndCheckCommitmentV3(ctx context.Context, header *types.Header, applyT if err != nil { return false, err } - minBlockNum = cmp.Max(minBlockNum, unwindToLimit) + minBlockNum = max(minBlockNum, unwindToLimit) // Binary search, but not too deep jump := cmp.InRange(1, 1000, (maxBlockNum-minBlockNum)/2) diff --git a/eth/stagedsync/stage_execute.go b/eth/stagedsync/stage_execute.go index 9bd542972e6..3ec300bb464 100644 --- a/eth/stagedsync/stage_execute.go +++ b/eth/stagedsync/stage_execute.go @@ -9,25 +9,25 @@ import ( "time" "github.com/c2h5oh/datasize" - "github.com/ledgerwatch/erigon-lib/config3" - "github.com/ledgerwatch/erigon-lib/kv/temporal" "github.com/ledgerwatch/log/v3" "golang.org/x/sync/errgroup" "github.com/ledgerwatch/erigon-lib/chain" "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/common/datadir" "github.com/ledgerwatch/erigon-lib/common/dbg" "github.com/ledgerwatch/erigon-lib/common/metrics" + "github.com/ledgerwatch/erigon-lib/config3" "github.com/ledgerwatch/erigon-lib/diagnostics" "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon-lib/kv/dbutils" "github.com/ledgerwatch/erigon-lib/kv/membatch" "github.com/ledgerwatch/erigon-lib/kv/membatchwithdb" "github.com/ledgerwatch/erigon-lib/kv/rawdbv3" + "github.com/ledgerwatch/erigon-lib/kv/temporal" libstate "github.com/ledgerwatch/erigon-lib/state" "github.com/ledgerwatch/erigon-lib/wrap" + "github.com/ledgerwatch/erigon/consensus" "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/rawdb" @@ -286,7 +286,7 @@ func ExecBlockV3(s *StageState, u Unwinder, txc wrap.TxContainer, toBlock uint64 var to = prevStageProgress if toBlock > 0 { - to = cmp.Min(prevStageProgress, toBlock) + to = min(prevStageProgress, toBlock) } if to < s.BlockNumber { return nil @@ -305,7 +305,7 @@ func reconstituteBlock(agg *libstate.Aggregator, db kv.RoDB, tx kv.Tx) (n uint64 if err != nil { return 0, false, err } - reconToBlock := cmp.Min(sendersProgress, agg.EndTxNumDomainsFrozen()) + reconToBlock := min(sendersProgress, agg.EndTxNumDomainsFrozen()) if tx == nil { if err = db.View(context.Background(), func(tx kv.Tx) error { ok, n, err = rawdbv3.TxNums.FindBlockNum(tx, reconToBlock) @@ -434,7 +434,7 @@ func SpawnExecuteBlocksStage(s *StageState, u Unwinder, txc wrap.TxContainer, to var to = prevStageProgress if toBlock > 0 { - to = cmp.Min(prevStageProgress, toBlock) + to = min(prevStageProgress, toBlock) } if cfg.syncCfg.LoopBlockLimit > 0 { diff --git a/eth/stagedsync/stage_senders.go b/eth/stagedsync/stage_senders.go index c003875cc01..7b382fbffeb 100644 --- a/eth/stagedsync/stage_senders.go +++ b/eth/stagedsync/stage_senders.go @@ -9,26 +9,25 @@ import ( "sync" "time" - "github.com/ledgerwatch/erigon-lib/kv/dbutils" - "github.com/ledgerwatch/erigon/eth/ethconfig" + "github.com/ledgerwatch/log/v3" + "github.com/ledgerwatch/secp256k1" "github.com/ledgerwatch/erigon-lib/chain" libcommon "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/common/hexutility" "github.com/ledgerwatch/erigon-lib/common/length" "github.com/ledgerwatch/erigon-lib/etl" "github.com/ledgerwatch/erigon-lib/kv" - "github.com/ledgerwatch/erigon/consensus" - "github.com/ledgerwatch/erigon/turbo/services" - "github.com/ledgerwatch/log/v3" - "github.com/ledgerwatch/secp256k1" + "github.com/ledgerwatch/erigon-lib/kv/dbutils" "github.com/ledgerwatch/erigon/common/debug" + "github.com/ledgerwatch/erigon/consensus" "github.com/ledgerwatch/erigon/core/rawdb" "github.com/ledgerwatch/erigon/core/types" + "github.com/ledgerwatch/erigon/eth/ethconfig" "github.com/ledgerwatch/erigon/eth/stagedsync/stages" "github.com/ledgerwatch/erigon/ethdb/prune" + "github.com/ledgerwatch/erigon/turbo/services" "github.com/ledgerwatch/erigon/turbo/stages/headerdownload" ) @@ -94,7 +93,7 @@ func SpawnRecoverSendersStage(cfg SendersCfg, s *StageState, u Unwinder, tx kv.R var to = prevStageProgress if toBlock > 0 { - to = cmp.Min(prevStageProgress, toBlock) + to = min(prevStageProgress, toBlock) } if to < s.BlockNumber { return nil diff --git a/eth/stagedsync/stage_txlookup.go b/eth/stagedsync/stage_txlookup.go index 44a35ae3849..7d729c5f468 100644 --- a/eth/stagedsync/stage_txlookup.go +++ b/eth/stagedsync/stage_txlookup.go @@ -10,7 +10,6 @@ import ( "github.com/ledgerwatch/erigon-lib/chain" libcommon "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/common/hexutility" "github.com/ledgerwatch/erigon-lib/etl" "github.com/ledgerwatch/erigon-lib/kv" @@ -68,7 +67,7 @@ func SpawnTxLookup(s *StageState, tx kv.RwTx, toBlock uint64, cfg TxLookupCfg, c return err } if toBlock > 0 { - endBlock = cmp.Min(endBlock, toBlock) + endBlock = min(endBlock, toBlock) } startBlock := s.BlockNumber @@ -194,7 +193,7 @@ func UnwindTxLookup(u *UnwindState, s *StageState, tx kv.RwTx, cfg TxLookupCfg, blockFrom, blockTo := u.UnwindPoint+1, s.BlockNumber+1 if cfg.blockReader.FreezingCfg().Enabled { smallestInDB := cfg.blockReader.FrozenBlocks() - blockFrom, blockTo = cmp.Max(blockFrom, smallestInDB), cmp.Max(blockTo, smallestInDB) + blockFrom, blockTo = max(blockFrom, smallestInDB), max(blockTo, smallestInDB) } // etl.Transform uses ExtractEndKey as exclusive bound, therefore blockTo + 1 if err := deleteTxLookupRange(tx, s.LogPrefix(), blockFrom, blockTo+1, ctx, cfg, logger); err != nil { @@ -238,7 +237,7 @@ func PruneTxLookup(s *PruneState, tx kv.RwTx, cfg TxLookupCfg, ctx context.Conte blockTo = cfg.blockReader.CanPruneTo(s.ForwardProgress) } // can't prune much here: because tx_lookup index has crypto-hashed-keys, and 1 block producing hundreds of deletes - blockTo = cmp.Min(blockTo, blockFrom+10) + blockTo = min(blockTo, blockFrom+10) if blockFrom < blockTo { if err = deleteTxLookupRange(tx, logPrefix, blockFrom, blockTo, ctx, cfg, logger); err != nil { diff --git a/p2p/discover/v5_udp.go b/p2p/discover/v5_udp.go index 6e56097e331..7b7787f1644 100644 --- a/p2p/discover/v5_udp.go +++ b/p2p/discover/v5_udp.go @@ -29,14 +29,14 @@ import ( "sync" "time" - common2 "github.com/ledgerwatch/erigon-lib/common/cmp" + "github.com/ledgerwatch/log/v3" + "github.com/ledgerwatch/erigon/common/debug" "github.com/ledgerwatch/erigon/common/mclock" "github.com/ledgerwatch/erigon/p2p/discover/v5wire" "github.com/ledgerwatch/erigon/p2p/enode" "github.com/ledgerwatch/erigon/p2p/enr" "github.com/ledgerwatch/erigon/p2p/netutil" - "github.com/ledgerwatch/log/v3" ) const ( @@ -407,7 +407,7 @@ func (t *UDPv5) waitForNodes(c *callV5, distances []uint) ([]*enode.Node, error) nodes = append(nodes, node) } if total == -1 { - total = common2.Min(int(response.Total), totalNodesResponseLimit) + total = min(int(response.Total), totalNodesResponseLimit) } if received++; received == total { return nodes, nil @@ -859,7 +859,7 @@ func packNodes(reqid []byte, nodes []*enode.Node) []*v5wire.Nodes { var resp []*v5wire.Nodes for len(nodes) > 0 { p := &v5wire.Nodes{ReqID: reqid, Total: total} - items := common2.Min(nodesResponseItemLimit, len(nodes)) + items := min(nodesResponseItemLimit, len(nodes)) for i := 0; i < items; i++ { p.Nodes = append(p.Nodes, nodes[i].Record()) } diff --git a/polygon/heimdall/heimdall_test.go b/polygon/heimdall/heimdall_test.go index 7dac40953cd..449d769063f 100644 --- a/polygon/heimdall/heimdall_test.go +++ b/polygon/heimdall/heimdall_test.go @@ -12,7 +12,6 @@ import ( "go.uber.org/mock/gomock" libcommon "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon/crypto" ) @@ -93,7 +92,7 @@ func (test heimdallTest) setupCheckpoints(count int) []*Checkpoint { return nil, nil } - limit = cmp.Min(10, limit) + limit = min(10, limit) l := (page - 1) * limit r := page * limit return expectedCheckpoints[l:r], nil diff --git a/polygon/p2p/fetcher_base.go b/polygon/p2p/fetcher_base.go index a313e0cfa4e..ac09f31d6c2 100644 --- a/polygon/p2p/fetcher_base.go +++ b/polygon/p2p/fetcher_base.go @@ -10,7 +10,6 @@ import ( "github.com/cenkalti/backoff/v4" "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon/core/types" "github.com/ledgerwatch/erigon/eth/protocols/eth" ) @@ -92,7 +91,7 @@ func (f *fetcher) FetchHeaders(ctx context.Context, start uint64, end uint64, pe headers := make([]*types.Header, 0, amount) for chunkNum := uint64(0); chunkNum < numChunks; chunkNum++ { chunkStart := start + chunkNum*eth.MaxHeadersServe - chunkEnd := cmp.Min(end, chunkStart+eth.MaxHeadersServe) + chunkEnd := min(end, chunkStart+eth.MaxHeadersServe) for chunkStart < chunkEnd { // a node may not respond with all MaxHeadersServe in 1 response, // so we keep on consuming from last received number (akin to consuming a paging api) diff --git a/polygon/sync/block_downloader.go b/polygon/sync/block_downloader.go index bbd9ba2a338..356119341f6 100644 --- a/polygon/sync/block_downloader.go +++ b/polygon/sync/block_downloader.go @@ -14,7 +14,6 @@ import ( "github.com/ledgerwatch/log/v3" "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon/core/types" "github.com/ledgerwatch/erigon/eth/ethconfig/estimate" "github.com/ledgerwatch/erigon/polygon/heimdall" @@ -165,7 +164,7 @@ func (d *blockDownloader) downloadBlocksUsingWaypoints( continue } - numWorkers := cmp.Min(cmp.Min(d.maxWorkers, len(peers)), len(waypoints)) + numWorkers := min(d.maxWorkers, len(peers), len(waypoints)) waypointsBatch := waypoints[:numWorkers] select { @@ -194,7 +193,7 @@ func (d *blockDownloader) downloadBlocksUsingWaypoints( maxWaypointLength := uint64(0) wg := sync.WaitGroup{} for i, waypoint := range waypointsBatch { - maxWaypointLength = cmp.Max(waypoint.Length(), maxWaypointLength) + maxWaypointLength = max(waypoint.Length(), maxWaypointLength) wg.Add(1) go func(i int, waypoint heimdall.Waypoint, peerId *p2p.PeerId) { defer wg.Done() diff --git a/turbo/jsonrpc/otterscan_contract_creator.go b/turbo/jsonrpc/otterscan_contract_creator.go index f64abf4828e..04a90134268 100644 --- a/turbo/jsonrpc/otterscan_contract_creator.go +++ b/turbo/jsonrpc/otterscan_contract_creator.go @@ -5,12 +5,12 @@ import ( "fmt" "sort" + "github.com/ledgerwatch/log/v3" + "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon-lib/kv/order" "github.com/ledgerwatch/erigon-lib/kv/rawdbv3" - "github.com/ledgerwatch/log/v3" "github.com/ledgerwatch/erigon/core/types/accounts" "github.com/ledgerwatch/erigon/turbo/rpchelper" @@ -127,7 +127,7 @@ func (api *OtterscanAPIImpl) GetContractCreator(ctx context.Context, addr common return false } if len(v) == 0 { - creationTxnID = cmp.Max(creationTxnID, txnID) + creationTxnID = max(creationTxnID, txnID) return false } @@ -136,7 +136,7 @@ func (api *OtterscanAPIImpl) GetContractCreator(ctx context.Context, addr common return false } if acc.Incarnation < plainStateAcc.Incarnation { - creationTxnID = cmp.Max(creationTxnID, txnID) + creationTxnID = max(creationTxnID, txnID) return false } return true diff --git a/turbo/jsonrpc/otterscan_transaction_by_sender_and_nonce.go b/turbo/jsonrpc/otterscan_transaction_by_sender_and_nonce.go index b0fee2d20a8..2bea5333781 100644 --- a/turbo/jsonrpc/otterscan_transaction_by_sender_and_nonce.go +++ b/turbo/jsonrpc/otterscan_transaction_by_sender_and_nonce.go @@ -5,12 +5,12 @@ import ( "fmt" "sort" + "github.com/ledgerwatch/log/v3" + "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon-lib/kv/order" "github.com/ledgerwatch/erigon-lib/kv/rawdbv3" - "github.com/ledgerwatch/log/v3" "github.com/ledgerwatch/erigon/core/types/accounts" ) @@ -90,7 +90,7 @@ func (api *OtterscanAPIImpl) GetTransactionBySenderAndNonce(ctx context.Context, return false } if len(v) == 0 { - creationTxnID = cmp.Max(creationTxnID, txnID) + creationTxnID = max(creationTxnID, txnID) return false } @@ -104,7 +104,7 @@ func (api *OtterscanAPIImpl) GetTransactionBySenderAndNonce(ctx context.Context, // previous history block contains the actual change; it may contain multiple // nonce changes. if acc.Nonce <= nonce { - creationTxnID = cmp.Max(creationTxnID, txnID) + creationTxnID = max(creationTxnID, txnID) return false } return true diff --git a/turbo/snapshotsync/freezeblocks/block_snapshots.go b/turbo/snapshotsync/freezeblocks/block_snapshots.go index 4e6f4bac965..1529b00dbb7 100644 --- a/turbo/snapshotsync/freezeblocks/block_snapshots.go +++ b/turbo/snapshotsync/freezeblocks/block_snapshots.go @@ -1140,7 +1140,7 @@ func chooseSegmentEnd(from, to uint64, snapType snaptype.Enum, chainConfig *chai blocksPerFile := snapcfg.MergeLimit(chainName, snapType, from) next := (from/blocksPerFile + 1) * blocksPerFile - to = cmp.Min(next, to) + to = min(next, to) if to < snaptype.Erigon2MinSegmentSize { return to @@ -1246,7 +1246,7 @@ func canRetire(from, to uint64, snapType snaptype.Enum, chainConfig *chain.Confi maxJump = 10_000 } //roundedTo1K := (to / 1_000) * 1_000 - jump := cmp.Min(maxJump, roundedTo1K-blockFrom) + jump := min(maxJump, roundedTo1K-blockFrom) switch { // only next segment sizes are allowed case jump >= mergeLimit: blockTo = blockFrom + mergeLimit @@ -1273,7 +1273,7 @@ func CanDeleteTo(curBlockNum uint64, blocksInSnapshots uint64) (blockTo uint64) return blocksInSnapshots + 1 } hardLimit := (curBlockNum/1_000)*1_000 - keep - return cmp.Min(hardLimit, blocksInSnapshots+1) + return min(hardLimit, blocksInSnapshots+1) } func (br *BlockRetire) dbHasEnoughDataForBlocksRetire(ctx context.Context) (bool, error) { @@ -1437,7 +1437,7 @@ func (br *BlockRetire) RetireBlocks(ctx context.Context, minBlockNum uint64, max for { var ok, okBor bool - minBlockNum = cmp.Max(br.blockReader.FrozenBlocks(), minBlockNum) + minBlockNum = max(br.blockReader.FrozenBlocks(), minBlockNum) maxBlockNum = br.maxScheduledBlock.Load() if includeBor { @@ -1454,7 +1454,7 @@ func (br *BlockRetire) RetireBlocks(ctx context.Context, minBlockNum uint64, max } if includeBor { - minBorBlockNum := cmp.Max(br.blockReader.FrozenBorBlocks(), minBlockNum) + minBorBlockNum := max(br.blockReader.FrozenBorBlocks(), minBlockNum) okBor, err = br.retireBorBlocks(ctx, minBorBlockNum, maxBlockNum, lvl, seedNewSnapshots, onDeleteSnapshots) if err != nil { return err diff --git a/turbo/snapshotsync/freezeblocks/caplin_snapshots.go b/turbo/snapshotsync/freezeblocks/caplin_snapshots.go index 5feb898bee1..0c3784e2258 100644 --- a/turbo/snapshotsync/freezeblocks/caplin_snapshots.go +++ b/turbo/snapshotsync/freezeblocks/caplin_snapshots.go @@ -12,19 +12,19 @@ import ( "sync/atomic" "github.com/klauspost/compress/zstd" - "github.com/ledgerwatch/erigon-lib/common/datadir" "github.com/ledgerwatch/log/v3" "github.com/ledgerwatch/erigon-lib/chain/snapcfg" libcommon "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/common/background" - "github.com/ledgerwatch/erigon-lib/common/cmp" + "github.com/ledgerwatch/erigon-lib/common/datadir" "github.com/ledgerwatch/erigon-lib/common/dbg" "github.com/ledgerwatch/erigon-lib/downloader/snaptype" "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon-lib/kv/dbutils" "github.com/ledgerwatch/erigon-lib/recsplit" "github.com/ledgerwatch/erigon-lib/seg" + "github.com/ledgerwatch/erigon/cl/clparams" "github.com/ledgerwatch/erigon/cl/cltypes" "github.com/ledgerwatch/erigon/cl/persistence/beacon_indicies" @@ -107,7 +107,7 @@ func (s *CaplinSnapshots) SegFilePaths(from, to uint64) []string { } func (s *CaplinSnapshots) BlocksAvailable() uint64 { - return cmp.Min(s.segmentsMax.Load(), s.idxMax.Load()) + return min(s.segmentsMax.Load(), s.idxMax.Load()) } func (s *CaplinSnapshots) Close() { diff --git a/turbo/trie/trie.go b/turbo/trie/trie.go index c8e6ee215e4..2c55237a943 100644 --- a/turbo/trie/trie.go +++ b/turbo/trie/trie.go @@ -23,7 +23,6 @@ import ( "fmt" libcommon "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/common/cmp" "github.com/ledgerwatch/erigon/core/types/accounts" "github.com/ledgerwatch/erigon/crypto" @@ -874,7 +873,7 @@ func (t *Trie) deleteRecursive(origNode node, key []byte, keyStart int, preserve switch n := origNode.(type) { case *shortNode: matchlen := prefixLen(key[keyStart:], n.Key) - if matchlen == cmp.Min(len(n.Key), len(key[keyStart:])) || n.Key[matchlen] == 16 || key[keyStart+matchlen] == 16 { + if matchlen == min(len(n.Key), len(key[keyStart:])) || n.Key[matchlen] == 16 || key[keyStart+matchlen] == 16 { fullMatch := matchlen == len(key)-keyStart removeNodeEntirely := fullMatch if preserveAccountNode { From dcdbe45ae3ce676074fb7998a6156c1f2b27e175 Mon Sep 17 00:00:00 2001 From: yperbasis Date: Tue, 28 May 2024 22:44:37 +0200 Subject: [PATCH 3/3] kill min64/max64 --- cl/antiquary/antiquary.go | 7 ++- cl/cltypes/solid/uint64slice_byte.go | 4 +- cl/cltypes/solid/validator_set.go | 2 +- cl/phase1/core/state/accessors.go | 4 +- cl/phase1/core/state/cache.go | 2 +- cl/phase1/core/state/cache_accessors.go | 4 +- cl/phase1/core/state/cache_mutators.go | 3 +- cl/phase1/core/state/util.go | 8 ++- .../services/sync_contribution_service.go | 2 +- .../process_effective_balance_update.go | 3 +- .../statechange/process_inactivity_scores.go | 5 +- cl/utils/math.go | 14 ----- cl/utils/math_test.go | 51 ------------------- cmd/capcli/cli.go | 35 ++++++------- erigon-lib/state/btree_index.go | 11 +--- .../freezeblocks/caplin_snapshots.go | 3 +- 16 files changed, 37 insertions(+), 121 deletions(-) diff --git a/cl/antiquary/antiquary.go b/cl/antiquary/antiquary.go index dd69236362a..0886a434a6c 100644 --- a/cl/antiquary/antiquary.go +++ b/cl/antiquary/antiquary.go @@ -6,6 +6,7 @@ import ( "sync/atomic" "time" + "github.com/ledgerwatch/log/v3" "golang.org/x/sync/semaphore" "github.com/ledgerwatch/erigon-lib/common/datadir" @@ -17,9 +18,7 @@ import ( "github.com/ledgerwatch/erigon/cl/persistence/blob_storage" state_accessors "github.com/ledgerwatch/erigon/cl/persistence/state" "github.com/ledgerwatch/erigon/cl/phase1/core/state" - "github.com/ledgerwatch/erigon/cl/utils" "github.com/ledgerwatch/erigon/turbo/snapshotsync/freezeblocks" - "github.com/ledgerwatch/log/v3" ) const safetyMargin = 2_000 // We retire snapshots 2k blocks after the finalized head @@ -214,7 +213,7 @@ func (a *Antiquary) Loop() error { if from >= to { continue } - to = utils.Min64(to, to-safetyMargin) // We don't want to retire snapshots that are too close to the finalized head + to = min(to, to-safetyMargin) // We don't want to retire snapshots that are too close to the finalized head to = (to / snaptype.Erigon2MergeLimit) * snaptype.Erigon2MergeLimit if to-from < snaptype.Erigon2MergeLimit { continue @@ -320,7 +319,7 @@ func (a *Antiquary) antiquateBlobs() error { // perform blob antiquation if it is time to. currentBlobsProgress := a.sn.FrozenBlobs() minimunBlobsProgress := ((a.cfg.DenebForkEpoch * a.cfg.SlotsPerEpoch) / snaptype.Erigon2MergeLimit) * snaptype.Erigon2MergeLimit - currentBlobsProgress = utils.Max64(currentBlobsProgress, minimunBlobsProgress) + currentBlobsProgress = max(currentBlobsProgress, minimunBlobsProgress) // read the finalized head to, err := beacon_indicies.ReadHighestFinalized(roTx) if err != nil { diff --git a/cl/cltypes/solid/uint64slice_byte.go b/cl/cltypes/solid/uint64slice_byte.go index 3fd39423745..b1c7d32902f 100644 --- a/cl/cltypes/solid/uint64slice_byte.go +++ b/cl/cltypes/solid/uint64slice_byte.go @@ -195,14 +195,14 @@ func (arr *byteBasedUint64Slice) HashVectorSSZ() ([32]byte, error) { for i := 0; i < maxTo; i += chunkSize { offset = (i / chunkSize) * length.Hash from := i - to := int(utils.Min64(uint64(from+chunkSize), uint64(maxTo))) + to := min(from+chunkSize, maxTo) if !bytes.Equal(arr.treeCacheBuffer[offset:offset+length.Hash], emptyHashBytes) { continue } layerBuffer = layerBuffer[:to-from] copy(layerBuffer, arr.u[from:to]) - if err := computeFlatRootsToBuffer(uint8(utils.Min64(treeCacheDepthUint64Slice, uint64(depth))), layerBuffer, arr.treeCacheBuffer[offset:]); err != nil { + if err := computeFlatRootsToBuffer(uint8(min(treeCacheDepthUint64Slice, uint64(depth))), layerBuffer, arr.treeCacheBuffer[offset:]); err != nil { return [32]byte{}, err } } diff --git a/cl/cltypes/solid/validator_set.go b/cl/cltypes/solid/validator_set.go index eb5b6e170d1..894dec42dc7 100644 --- a/cl/cltypes/solid/validator_set.go +++ b/cl/cltypes/solid/validator_set.go @@ -187,7 +187,7 @@ func (v *ValidatorSet) HashSSZ() ([32]byte, error) { layerBuffer := make([]byte, validatorsLeafChunkSize*length.Hash) for i := 0; i < v.l; i += validatorsLeafChunkSize { from := uint64(i) - to := utils.Min64(from+uint64(validatorsLeafChunkSize), uint64(v.l)) + to := min(from+uint64(validatorsLeafChunkSize), uint64(v.l)) offset := (i / validatorsLeafChunkSize) * length.Hash if !bytes.Equal(v.treeCacheBuffer[offset:offset+length.Hash], emptyHashBytes) { diff --git a/cl/phase1/core/state/accessors.go b/cl/phase1/core/state/accessors.go index 7d08c683235..cca52d504a4 100644 --- a/cl/phase1/core/state/accessors.go +++ b/cl/phase1/core/state/accessors.go @@ -30,7 +30,7 @@ func Epoch(b abstract.BeaconStateBasic) uint64 { } func IsAggregator(cfg *clparams.BeaconChainConfig, committeeLength, committeeIndex uint64, slotSignature libcommon.Bytes96) bool { - modulo := utils.Max64(1, committeeLength/cfg.TargetAggregatorsPerCommittee) + modulo := max(1, committeeLength/cfg.TargetAggregatorsPerCommittee) hashSlotSignatue := utils.Sha256(slotSignature[:]) return binary.LittleEndian.Uint64(hashSlotSignatue[:8])%modulo == 0 } @@ -208,7 +208,7 @@ func ExpectedWithdrawals(b abstract.BeaconState, currentEpoch uint64) []*cltypes // Determine the upper bound for the loop and initialize the withdrawals slice with a capacity of bound maxValidators := uint64(b.ValidatorLength()) maxValidatorsPerWithdrawalsSweep := b.BeaconConfig().MaxValidatorsPerWithdrawalsSweep - bound := utils.Min64(maxValidators, maxValidatorsPerWithdrawalsSweep) + bound := min(maxValidators, maxValidatorsPerWithdrawalsSweep) withdrawals := make([]*cltypes.Withdrawal, 0, bound) // Loop through the validators to calculate expected withdrawals diff --git a/cl/phase1/core/state/cache.go b/cl/phase1/core/state/cache.go index 70e05d7bc7e..c0424442828 100644 --- a/cl/phase1/core/state/cache.go +++ b/cl/phase1/core/state/cache.go @@ -203,7 +203,7 @@ func (b *CachingBeaconState) _refreshActiveBalancesIfNeeded() { } return true }) - *b.totalActiveBalanceCache = utils.Max64(b.BeaconConfig().EffectiveBalanceIncrement, *b.totalActiveBalanceCache) + *b.totalActiveBalanceCache = max(b.BeaconConfig().EffectiveBalanceIncrement, *b.totalActiveBalanceCache) b.totalActiveBalanceRootCache = utils.IntegerSquareRoot(*b.totalActiveBalanceCache) } diff --git a/cl/phase1/core/state/cache_accessors.go b/cl/phase1/core/state/cache_accessors.go index e72bcec31d0..ed9c9a9abdd 100644 --- a/cl/phase1/core/state/cache_accessors.go +++ b/cl/phase1/core/state/cache_accessors.go @@ -340,7 +340,7 @@ func (b *CachingBeaconState) GetAttestingIndicies( // See: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#get_validator_churn_limit func (b *CachingBeaconState) GetValidatorChurnLimit() uint64 { activeIndsCount := uint64(len(b.GetActiveValidatorsIndices(Epoch(b)))) - return utils.Max64( + return max( activeIndsCount/b.BeaconConfig().ChurnLimitQuotient, b.BeaconConfig().MinPerEpochChurnLimit, ) @@ -349,7 +349,7 @@ func (b *CachingBeaconState) GetValidatorChurnLimit() uint64 { // https://github.com/ethereum/consensus-specs/blob/dev/specs/deneb/beacon-chain.md#new-get_validator_activation_churn_limit func (b *CachingBeaconState) GetValidatorActivationChurnLimit() uint64 { if b.Version() >= clparams.DenebVersion { - return utils.Min64( + return min( b.BeaconConfig().MaxPerEpochActivationChurnLimit, b.GetValidatorChurnLimit(), ) diff --git a/cl/phase1/core/state/cache_mutators.go b/cl/phase1/core/state/cache_mutators.go index b5ee40db296..4059da582ec 100644 --- a/cl/phase1/core/state/cache_mutators.go +++ b/cl/phase1/core/state/cache_mutators.go @@ -6,7 +6,6 @@ import ( "github.com/ledgerwatch/erigon-lib/common/math" "github.com/ledgerwatch/erigon/cl/clparams" "github.com/ledgerwatch/erigon/cl/cltypes/solid" - "github.com/ledgerwatch/erigon/cl/utils" ) func (b *CachingBeaconState) getSlashingProposerReward(whistleBlowerReward uint64) uint64 { @@ -34,7 +33,7 @@ func (b *CachingBeaconState) SlashValidator(slashedInd uint64, whistleblowerInd return 0, err } - newWithdrawableEpoch := utils.Max64(currentWithdrawableEpoch, epoch+b.BeaconConfig().EpochsPerSlashingsVector) + newWithdrawableEpoch := max(currentWithdrawableEpoch, epoch+b.BeaconConfig().EpochsPerSlashingsVector) if err := b.SetWithdrawableEpochForValidatorAtIndex(int(slashedInd), newWithdrawableEpoch); err != nil { return 0, err } diff --git a/cl/phase1/core/state/util.go b/cl/phase1/core/state/util.go index 9a6c684a863..b74fb9b7399 100644 --- a/cl/phase1/core/state/util.go +++ b/cl/phase1/core/state/util.go @@ -3,12 +3,10 @@ package state import ( "sort" - "github.com/ledgerwatch/erigon/cl/cltypes/solid" - "github.com/ledgerwatch/erigon/cl/phase1/core/state/lru" - "github.com/ledgerwatch/erigon/cl/clparams" "github.com/ledgerwatch/erigon/cl/cltypes" - "github.com/ledgerwatch/erigon/cl/utils" + "github.com/ledgerwatch/erigon/cl/cltypes/solid" + "github.com/ledgerwatch/erigon/cl/phase1/core/state/lru" ) func copyLRU[K comparable, V any](dst *lru.Cache[K, V], src *lru.Cache[K, V]) *lru.Cache[K, V] { @@ -37,7 +35,7 @@ func GetIndexedAttestation(attestation *solid.Attestation, attestingIndicies []u func ValidatorFromDeposit(conf *clparams.BeaconChainConfig, deposit *cltypes.Deposit) solid.Validator { amount := deposit.Data.Amount - effectiveBalance := utils.Min64(amount-amount%conf.EffectiveBalanceIncrement, conf.MaxEffectiveBalance) + effectiveBalance := min(amount-amount%conf.EffectiveBalanceIncrement, conf.MaxEffectiveBalance) validator := solid.NewValidator() validator.SetPublicKey(deposit.Data.PubKey) diff --git a/cl/phase1/network/services/sync_contribution_service.go b/cl/phase1/network/services/sync_contribution_service.go index 0f37daf9924..8b61de8b773 100644 --- a/cl/phase1/network/services/sync_contribution_service.go +++ b/cl/phase1/network/services/sync_contribution_service.go @@ -101,7 +101,7 @@ func (s *syncContributionService) ProcessMessage(ctx context.Context, subnet *ui return fmt.Errorf("contribution has no participants") } - modulo := utils.Max64(1, s.beaconCfg.SyncCommitteeSize/s.beaconCfg.SyncCommitteeSubnetCount/s.beaconCfg.TargetAggregatorsPerSyncSubcommittee) + modulo := max(1, s.beaconCfg.SyncCommitteeSize/s.beaconCfg.SyncCommitteeSubnetCount/s.beaconCfg.TargetAggregatorsPerSyncSubcommittee) hashSignature := utils.Sha256(selectionProof[:]) if !s.test && binary.LittleEndian.Uint64(hashSignature[:8])%modulo != 0 { return fmt.Errorf("selects the validator as an aggregator") diff --git a/cl/transition/impl/eth2/statechange/process_effective_balance_update.go b/cl/transition/impl/eth2/statechange/process_effective_balance_update.go index 162707c1fc0..3091191f48f 100644 --- a/cl/transition/impl/eth2/statechange/process_effective_balance_update.go +++ b/cl/transition/impl/eth2/statechange/process_effective_balance_update.go @@ -3,7 +3,6 @@ package statechange import ( "github.com/ledgerwatch/erigon/cl/abstract" "github.com/ledgerwatch/erigon/cl/cltypes/solid" - "github.com/ledgerwatch/erigon/cl/utils" ) // ProcessEffectiveBalanceUpdates updates the effective balance of validators. Specs at: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#effective-balances-updates @@ -24,7 +23,7 @@ func ProcessEffectiveBalanceUpdates(state abstract.BeaconState) error { eb := validator.EffectiveBalance() if balance+downwardThreshold < eb || eb+upwardThreshold < balance { // Set new effective balance - effectiveBalance := utils.Min64(balance-(balance%beaconConfig.EffectiveBalanceIncrement), beaconConfig.MaxEffectiveBalance) + effectiveBalance := min(balance-(balance%beaconConfig.EffectiveBalanceIncrement), beaconConfig.MaxEffectiveBalance) state.SetEffectiveBalanceForValidatorAtIndex(index, effectiveBalance) } return true diff --git a/cl/transition/impl/eth2/statechange/process_inactivity_scores.go b/cl/transition/impl/eth2/statechange/process_inactivity_scores.go index bc81c5de789..38a3ed0e3b2 100644 --- a/cl/transition/impl/eth2/statechange/process_inactivity_scores.go +++ b/cl/transition/impl/eth2/statechange/process_inactivity_scores.go @@ -3,7 +3,6 @@ package statechange import ( "github.com/ledgerwatch/erigon/cl/abstract" "github.com/ledgerwatch/erigon/cl/phase1/core/state" - "github.com/ledgerwatch/erigon/cl/utils" ) // ProcessInactivityScores will updates the inactivity registry of each validator. @@ -19,12 +18,12 @@ func ProcessInactivityScores(s abstract.BeaconState, eligibleValidatorsIndicies return err } if unslashedIndicies[s.BeaconConfig().TimelyTargetFlagIndex][validatorIndex] { - score -= utils.Min64(1, score) + score -= min(1, score) } else { score += s.BeaconConfig().InactivityScoreBias } if !state.InactivityLeaking(s) { - score -= utils.Min64(s.BeaconConfig().InactivityScoreRecoveryRate, score) + score -= min(s.BeaconConfig().InactivityScoreRecoveryRate, score) } if err := s.SetValidatorInactivityScore(int(validatorIndex), score); err != nil { return err diff --git a/cl/utils/math.go b/cl/utils/math.go index 93df6f51bbf..32f4eac67ef 100644 --- a/cl/utils/math.go +++ b/cl/utils/math.go @@ -41,17 +41,3 @@ func IntegerSquareRoot(n uint64) uint64 { return uint64(math.Sqrt(float64(n))) } - -func Max64(a, b uint64) uint64 { - if a > b { - return a - } - return b -} - -func Min64(a, b uint64) uint64 { - if a < b { - return a - } - return b -} diff --git a/cl/utils/math_test.go b/cl/utils/math_test.go index 6b4a801ed9e..2cabadba7c0 100644 --- a/cl/utils/math_test.go +++ b/cl/utils/math_test.go @@ -1,7 +1,6 @@ package utils_test import ( - "math" "testing" "github.com/ledgerwatch/erigon/cl/utils" @@ -95,53 +94,3 @@ func TestIntegerSquareRoot(t *testing.T) { } } } - -func TestMax64(t *testing.T) { - testCases := []struct { - a uint64 - b uint64 - expected uint64 - }{ - {0, 0, 0}, - {0, 1, 1}, - {1, 0, 1}, - {1, 1, 1}, - {10, 5, 10}, - {5, 10, 10}, - {math.MaxUint64, 0, math.MaxUint64}, - {0, math.MaxUint64, math.MaxUint64}, - {math.MaxUint64, math.MaxUint64, math.MaxUint64}, - } - - for _, tc := range testCases { - max := utils.Max64(tc.a, tc.b) - if max != tc.expected { - t.Errorf("Max64 returned incorrect result for %d and %d. Expected: %d, Got: %d", tc.a, tc.b, tc.expected, max) - } - } -} - -func TestMin64(t *testing.T) { - testCases := []struct { - a uint64 - b uint64 - expected uint64 - }{ - {0, 0, 0}, - {0, 1, 0}, - {1, 0, 0}, - {1, 1, 1}, - {10, 5, 5}, - {5, 10, 5}, - {math.MaxUint64, 0, 0}, - {0, math.MaxUint64, 0}, - {math.MaxUint64, math.MaxUint64, math.MaxUint64}, - } - - for _, tc := range testCases { - min := utils.Min64(tc.a, tc.b) - if min != tc.expected { - t.Errorf("Min64 returned incorrect result for %d and %d. Expected: %d, Got: %d", tc.a, tc.b, tc.expected, min) - } - } -} diff --git a/cmd/capcli/cli.go b/cmd/capcli/cli.go index a7a833dab9f..53fd7b38807 100644 --- a/cmd/capcli/cli.go +++ b/cmd/capcli/cli.go @@ -13,25 +13,20 @@ import ( "strings" "time" - "github.com/ledgerwatch/erigon/common" - "github.com/ledgerwatch/erigon/turbo/debug" + "github.com/ledgerwatch/log/v3" + "github.com/spf13/afero" + "google.golang.org/grpc" libcommon "github.com/ledgerwatch/erigon-lib/common" - + "github.com/ledgerwatch/erigon-lib/common/datadir" + "github.com/ledgerwatch/erigon-lib/downloader/snaptype" + sentinel "github.com/ledgerwatch/erigon-lib/gointerfaces/sentinelproto" + "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon-lib/metrics" "github.com/ledgerwatch/erigon/cl/antiquary" "github.com/ledgerwatch/erigon/cl/clparams" "github.com/ledgerwatch/erigon/cl/clparams/initial_state" - "github.com/ledgerwatch/erigon/cl/utils/eth_clock" - "github.com/ledgerwatch/erigon/cmd/caplin/caplin1" - "github.com/ledgerwatch/erigon/eth/ethconfig" - "github.com/ledgerwatch/erigon/eth/ethconfig/estimate" - "github.com/ledgerwatch/erigon/turbo/snapshotsync/freezeblocks" - - "github.com/ledgerwatch/erigon-lib/common/datadir" - "github.com/ledgerwatch/erigon-lib/downloader/snaptype" - "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon/cl/persistence/beacon_indicies" "github.com/ledgerwatch/erigon/cl/persistence/format/snapshot_format" "github.com/ledgerwatch/erigon/cl/persistence/format/snapshot_format/getters" @@ -42,13 +37,13 @@ import ( "github.com/ledgerwatch/erigon/cl/phase1/network" "github.com/ledgerwatch/erigon/cl/phase1/stages" "github.com/ledgerwatch/erigon/cl/rpc" - "github.com/ledgerwatch/erigon/cl/utils" - - "github.com/ledgerwatch/log/v3" - "github.com/spf13/afero" - "google.golang.org/grpc" - - sentinel "github.com/ledgerwatch/erigon-lib/gointerfaces/sentinelproto" + "github.com/ledgerwatch/erigon/cl/utils/eth_clock" + "github.com/ledgerwatch/erigon/cmd/caplin/caplin1" + "github.com/ledgerwatch/erigon/common" + "github.com/ledgerwatch/erigon/eth/ethconfig" + "github.com/ledgerwatch/erigon/eth/ethconfig/estimate" + "github.com/ledgerwatch/erigon/turbo/debug" + "github.com/ledgerwatch/erigon/turbo/snapshotsync/freezeblocks" ) var CLI struct { @@ -378,7 +373,7 @@ func (c *CheckSnapshots) Run(ctx *Context) error { } previousBlockSlot := genesisHeader.Header.Slot for i := uint64(1); i < to; i++ { - if utils.Min64(0, i-320) > previousBlockSlot { + if min(0, i-320) > previousBlockSlot { return fmt.Errorf("snapshot %d has invalid slot", i) } // Checking of snapshots is a chain contiguity problem diff --git a/erigon-lib/state/btree_index.go b/erigon-lib/state/btree_index.go index da1029b7d8b..f1b7e807bc6 100644 --- a/erigon-lib/state/btree_index.go +++ b/erigon-lib/state/btree_index.go @@ -7,7 +7,6 @@ import ( "encoding/binary" "errors" "fmt" - "github.com/ledgerwatch/erigon-lib/common" "math" "os" "path" @@ -21,6 +20,7 @@ import ( "github.com/ledgerwatch/log/v3" "github.com/spaolacci/murmur3" + "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/common/background" "github.com/ledgerwatch/erigon-lib/common/dbg" "github.com/ledgerwatch/erigon-lib/etl" @@ -41,13 +41,6 @@ func logBase(n, base uint64) uint64 { return uint64(math.Ceil(math.Log(float64(n)) / math.Log(float64(base)))) } -func min64(a, b uint64) uint64 { - if a < b { - return a - } - return b -} - type markupCursor struct { l uint64 //l - level p uint64 //p - pos inside level @@ -183,7 +176,7 @@ func newBtAlloc(k, M uint64, trace bool, dataLookup dataLookupFunc, keyCmp keyCm //nnc := a.vx[i+1] / M //nvc := a.vx[i+1] / m //bvc := a.vx[i+1] / (m + (m >> 1)) - a.vx[i] = min64(uint64(math.Pow(float64(M), float64(i))), nnc) + a.vx[i] = min(uint64(math.Pow(float64(M), float64(i))), nnc) } ncount := uint64(0) diff --git a/turbo/snapshotsync/freezeblocks/caplin_snapshots.go b/turbo/snapshotsync/freezeblocks/caplin_snapshots.go index 0c3784e2258..e2691900b6c 100644 --- a/turbo/snapshotsync/freezeblocks/caplin_snapshots.go +++ b/turbo/snapshotsync/freezeblocks/caplin_snapshots.go @@ -30,7 +30,6 @@ import ( "github.com/ledgerwatch/erigon/cl/persistence/beacon_indicies" "github.com/ledgerwatch/erigon/cl/persistence/blob_storage" "github.com/ledgerwatch/erigon/cl/persistence/format/snapshot_format" - "github.com/ledgerwatch/erigon/cl/utils" "github.com/ledgerwatch/erigon/eth/ethconfig" ) @@ -644,7 +643,7 @@ func (s *CaplinSnapshots) FrozenBlobs() uint64 { if seg.from == minSegFrom { foundMinSeg = true } - ret = utils.Max64(ret, seg.to) + ret = max(ret, seg.to) } if !foundMinSeg { return 0