diff --git a/.github/workflows/build-linux-binaries.yml b/.github/workflows/build-linux-binaries.yml index 2c6e818a6a5a..3de0640df0ac 100644 --- a/.github/workflows/build-linux-binaries.yml +++ b/.github/workflows/build-linux-binaries.yml @@ -11,7 +11,7 @@ on: - "*" env: - go_version: '~1.20.12' + go_version: '~1.21.7' jobs: build-x86_64-binaries-tarball: diff --git a/.github/workflows/build-macos-release.yml b/.github/workflows/build-macos-release.yml index 06e9698cd423..c2ab2d39c7e9 100644 --- a/.github/workflows/build-macos-release.yml +++ b/.github/workflows/build-macos-release.yml @@ -26,7 +26,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: '~1.20.12' + go-version: '~1.21.7' check-latest: true - run: go version diff --git a/.github/workflows/build-public-ami.yml b/.github/workflows/build-public-ami.yml index bc08f71c93ec..410bebbde6ef 100644 --- a/.github/workflows/build-public-ami.yml +++ b/.github/workflows/build-public-ami.yml @@ -19,7 +19,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: '~1.20.12' + go-version: '~1.21.7' check-latest: true - run: go version diff --git a/.github/workflows/build-ubuntu-amd64-release.yml b/.github/workflows/build-ubuntu-amd64-release.yml index df0799c116f1..461a23b2e372 100644 --- a/.github/workflows/build-ubuntu-amd64-release.yml +++ b/.github/workflows/build-ubuntu-amd64-release.yml @@ -11,7 +11,7 @@ on: - "*" env: - go_version: '~1.20.12' + go_version: '~1.21.7' jobs: build-jammy-amd64-package: diff --git a/.github/workflows/build-ubuntu-arm64-release.yml b/.github/workflows/build-ubuntu-arm64-release.yml index 3e1987415a3e..588d0a70835f 100644 --- a/.github/workflows/build-ubuntu-arm64-release.yml +++ b/.github/workflows/build-ubuntu-arm64-release.yml @@ -11,7 +11,7 @@ on: - "*" env: - go_version: '~1.20.12' + go_version: '~1.21.7' jobs: build-jammy-arm64-package: diff --git a/.github/workflows/build-win-release.yml b/.github/workflows/build-win-release.yml index 6173eded586f..9038d4574094 100644 --- a/.github/workflows/build-win-release.yml +++ b/.github/workflows/build-win-release.yml @@ -26,7 +26,7 @@ jobs: - uses: actions/setup-go@v5 with: - go-version: '~1.20.12' + go-version: '~1.21.7' check-latest: true - run: go version diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d5466f8d1f84..34ab964130df 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,7 +20,7 @@ concurrency: cancel-in-progress: true env: - go_version: '~1.20.12' + go_version: '~1.21.7' tmpnet_data_path: ~/.tmpnet/networks/1000 jobs: diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 71b38eae780e..07c5d2dbfcb4 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -18,7 +18,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: '~1.20.12' + go-version: '~1.21.7' check-latest: true - name: Run fuzz tests shell: bash diff --git a/.github/workflows/fuzz_merkledb.yml b/.github/workflows/fuzz_merkledb.yml index c26b2e0002b3..09c58ffd38e0 100644 --- a/.github/workflows/fuzz_merkledb.yml +++ b/.github/workflows/fuzz_merkledb.yml @@ -20,7 +20,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: '~1.20.12' + go-version: '~1.21.7' check-latest: true - name: Run merkledb fuzz tests shell: bash diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2e850274d96f..3e509ed11064 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,7 +4,7 @@ To start developing on AvalancheGo, you'll need a few things installed. -- Golang version >= 1.20.12 +- Golang version >= 1.21.7 - gcc - g++ diff --git a/Dockerfile b/Dockerfile index a13fbddbd4f8..62594f64c766 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # README.md # go.mod # ============= Compilation Stage ================ -FROM golang:1.20.12-bullseye AS builder +FROM golang:1.21.7-bullseye AS builder WORKDIR /build # Copy and download avalanche dependencies using go mod diff --git a/README.md b/README.md index ac3cd62841a9..e1a38d67429d 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ The minimum recommended hardware specification for nodes connected to Mainnet is If you plan to build AvalancheGo from source, you will also need the following software: -- [Go](https://golang.org/doc/install) version >= 1.20.12 +- [Go](https://golang.org/doc/install) version >= 1.21.7 - [gcc](https://gcc.gnu.org/) - g++ diff --git a/api/health/worker.go b/api/health/worker.go index e42e77a4d52c..cbd47189fbcb 100644 --- a/api/health/worker.go +++ b/api/health/worker.go @@ -7,6 +7,8 @@ import ( "context" "errors" "fmt" + "maps" + "slices" "sync" "time" @@ -14,9 +16,6 @@ import ( "go.uber.org/zap" - "golang.org/x/exp/maps" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" @@ -167,7 +166,7 @@ func (w *worker) Results(tags ...string) (map[string]Result, bool) { func (w *worker) Start(ctx context.Context, freq time.Duration) { w.startOnce.Do(func() { - detachedCtx := utils.Detach(ctx) + detachedCtx := context.WithoutCancel(ctx) w.wg.Add(1) go func() { ticker := time.NewTicker(freq) diff --git a/api/metrics/multi_gatherer.go b/api/metrics/multi_gatherer.go index 45d4439622b4..a1b070791d21 100644 --- a/api/metrics/multi_gatherer.go +++ b/api/metrics/multi_gatherer.go @@ -4,17 +4,16 @@ package metrics import ( + "cmp" "errors" "fmt" + "slices" "sync" "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" - "golang.org/x/exp/slices" - - "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/metric" ) @@ -91,6 +90,6 @@ func (g *multiGatherer) Register(namespace string, gatherer prometheus.Gatherer) func sortMetrics(m []*dto.MetricFamily) { slices.SortFunc(m, func(i, j *dto.MetricFamily) int { - return utils.Compare(*i.Name, *j.Name) + return cmp.Compare(*i.Name, *j.Name) }) } diff --git a/chains/atomic/state.go b/chains/atomic/state.go index a9e9bbd05cd8..1eed23803fb7 100644 --- a/chains/atomic/state.go +++ b/chains/atomic/state.go @@ -7,8 +7,7 @@ import ( "bytes" "errors" "fmt" - - "golang.org/x/exp/slices" + "slices" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/linkeddb" diff --git a/codec/reflectcodec/type_codec.go b/codec/reflectcodec/type_codec.go index 312927559280..7f567d0bb7fa 100644 --- a/codec/reflectcodec/type_codec.go +++ b/codec/reflectcodec/type_codec.go @@ -9,10 +9,9 @@ import ( "fmt" "math" "reflect" + "slices" "time" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/wrappers" diff --git a/database/batch.go b/database/batch.go index 8699a90c2960..f3187a1fa954 100644 --- a/database/batch.go +++ b/database/batch.go @@ -7,7 +7,7 @@ package database -import "golang.org/x/exp/slices" +import "slices" // Batch is a write-only database that commits changes to its host database // when Write is called. A batch cannot be used concurrently. diff --git a/database/encdb/db.go b/database/encdb/db.go index 1b225b38f3cd..2bdacb465ffa 100644 --- a/database/encdb/db.go +++ b/database/encdb/db.go @@ -7,12 +7,11 @@ import ( "context" "crypto/cipher" "crypto/rand" + "slices" "sync" "golang.org/x/crypto/chacha20poly1305" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/utils/hashing" ) diff --git a/database/helpers_test.go b/database/helpers_test.go index 1ad3ccc2b20d..1cce64c82baf 100644 --- a/database/helpers_test.go +++ b/database/helpers_test.go @@ -5,13 +5,12 @@ package database import ( "math/rand" + "slices" "testing" "time" "github.com/stretchr/testify/require" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/utils" ) diff --git a/database/leveldb/db.go b/database/leveldb/db.go index 8ae825ef2fb1..2844ee97e9c4 100644 --- a/database/leveldb/db.go +++ b/database/leveldb/db.go @@ -9,6 +9,7 @@ import ( "encoding/json" "fmt" "math" + "slices" "sync" "time" @@ -23,8 +24,6 @@ import ( "go.uber.org/zap" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/logging" diff --git a/database/linkeddb/linkeddb.go b/database/linkeddb/linkeddb.go index f40498812cda..b7bc68679762 100644 --- a/database/linkeddb/linkeddb.go +++ b/database/linkeddb/linkeddb.go @@ -4,11 +4,9 @@ package linkeddb import ( + "slices" "sync" - "golang.org/x/exp/maps" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/cache" "github.com/ava-labs/avalanchego/database" ) @@ -339,7 +337,7 @@ func (ldb *linkedDB) deleteNode(key []byte) error { func (ldb *linkedDB) resetBatch() { ldb.headKeyIsUpdated = false - maps.Clear(ldb.updatedNodes) + clear(ldb.updatedNodes) ldb.batch.Reset() } diff --git a/database/memdb/db.go b/database/memdb/db.go index 914739f9e206..603fae118950 100644 --- a/database/memdb/db.go +++ b/database/memdb/db.go @@ -5,11 +5,10 @@ package memdb import ( "context" + "slices" "strings" "sync" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/database" ) diff --git a/database/pebble/db.go b/database/pebble/db.go index 4838ff4b0ffe..8f2aa631dd7a 100644 --- a/database/pebble/db.go +++ b/database/pebble/db.go @@ -8,14 +8,13 @@ import ( "context" "encoding/json" "errors" + "slices" "sync" "github.com/cockroachdb/pebble" "github.com/prometheus/client_golang/prometheus" - "golang.org/x/exp/slices" - "go.uber.org/zap" "github.com/ava-labs/avalanchego/database" diff --git a/database/pebble/iterator.go b/database/pebble/iterator.go index 5fc73f308a13..ab7d8aad11a3 100644 --- a/database/pebble/iterator.go +++ b/database/pebble/iterator.go @@ -6,12 +6,11 @@ package pebble import ( "errors" "fmt" + "slices" "sync" "github.com/cockroachdb/pebble" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/database" ) diff --git a/database/prefixdb/db.go b/database/prefixdb/db.go index d8af4b101900..8698453683ff 100644 --- a/database/prefixdb/db.go +++ b/database/prefixdb/db.go @@ -5,10 +5,9 @@ package prefixdb import ( "context" + "slices" "sync" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/utils/hashing" ) diff --git a/database/test_database.go b/database/test_database.go index 792b038012cb..d5bdca223f2c 100644 --- a/database/test_database.go +++ b/database/test_database.go @@ -8,6 +8,7 @@ import ( "io" "math" "math/rand" + "slices" "testing" "github.com/stretchr/testify/require" @@ -15,7 +16,6 @@ import ( "go.uber.org/mock/gomock" "golang.org/x/exp/maps" - "golang.org/x/exp/slices" "golang.org/x/sync/errgroup" diff --git a/database/versiondb/db.go b/database/versiondb/db.go index 479e8af814d1..16876a43a68a 100644 --- a/database/versiondb/db.go +++ b/database/versiondb/db.go @@ -5,12 +5,10 @@ package versiondb import ( "context" + "slices" "strings" "sync" - "golang.org/x/exp/maps" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/memdb" ) @@ -210,7 +208,7 @@ func (db *Database) Abort() { } func (db *Database) abort() { - maps.Clear(db.mem) + clear(db.mem) } // CommitBatch returns a batch that contains all uncommitted puts/deletes. diff --git a/genesis/bootstrappers.go b/genesis/bootstrappers.go index b3e3a2a24f0c..4f39279ebfdd 100644 --- a/genesis/bootstrappers.go +++ b/genesis/bootstrappers.go @@ -12,7 +12,6 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/ips" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/sampler" ) @@ -45,7 +44,7 @@ func GetBootstrappers(networkID uint32) []Bootstrapper { // SampleBootstrappers returns the some beacons this node should connect to func SampleBootstrappers(networkID uint32, count int) []Bootstrapper { bootstrappers := GetBootstrappers(networkID) - count = math.Min(count, len(bootstrappers)) + count = min(count, len(bootstrappers)) s := sampler.NewUniform() s.Initialize(uint64(len(bootstrappers))) diff --git a/genesis/config.go b/genesis/config.go index 6e8ea15e7432..62b57c77f923 100644 --- a/genesis/config.go +++ b/genesis/config.go @@ -4,6 +4,7 @@ package genesis import ( + "cmp" "encoding/base64" "encoding/hex" "encoding/json" @@ -54,7 +55,7 @@ func (a Allocation) Unparse(networkID uint32) (UnparsedAllocation, error) { } func (a Allocation) Compare(other Allocation) int { - if amountCmp := utils.Compare(a.InitialAmount, other.InitialAmount); amountCmp != 0 { + if amountCmp := cmp.Compare(a.InitialAmount, other.InitialAmount); amountCmp != 0 { return amountCmp } return a.AVAXAddr.Compare(other.AVAXAddr) diff --git a/go.mod b/go.mod index 777107b13302..d2bade11b343 100644 --- a/go.mod +++ b/go.mod @@ -5,13 +5,13 @@ module github.com/ava-labs/avalanchego // Dockerfile // README.md // go.mod (here, only major.minor can be specified) -go 1.20 +go 1.21 require ( github.com/DataDog/zstd v1.5.2 github.com/Microsoft/go-winio v0.5.2 github.com/NYTimes/gziphandler v1.1.1 - github.com/ava-labs/coreth v0.12.11-rc.2 + github.com/ava-labs/coreth v0.12.11-rc.3.0.20240207021717-15431782181b github.com/ava-labs/ledger-avalanche/go v0.0.0-20231102202641-ae2ebdaeac34 github.com/btcsuite/btcd/btcutil v1.1.3 github.com/cockroachdb/pebble v0.0.0-20230209160836-829675f94811 diff --git a/go.sum b/go.sum index 55a473140252..3efac349b669 100644 --- a/go.sum +++ b/go.sum @@ -66,8 +66,8 @@ github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/coreth v0.12.11-rc.2 h1:roDTUOuTLoku4FYr7icHh2IMkxk2GRAqUocGZCXh2Mw= -github.com/ava-labs/coreth v0.12.11-rc.2/go.mod h1:YEYzy0l/7ig9gKV2P9yxzucnIml1TUa4L8foGQ15KO0= +github.com/ava-labs/coreth v0.12.11-rc.3.0.20240207021717-15431782181b h1:CG09kjMyp0+5iusoZZVyOc1tL1HtuiJ8cL/5QipQUD8= +github.com/ava-labs/coreth v0.12.11-rc.3.0.20240207021717-15431782181b/go.mod h1:ofm30knZFS5q+y3YS+p2jLa+3ZpgzW5OkM8He5MwZxs= github.com/ava-labs/ledger-avalanche/go v0.0.0-20231102202641-ae2ebdaeac34 h1:mg9Uw6oZFJKytJxgxnl3uxZOs/SB8CVHg6Io4Tf99Zc= github.com/ava-labs/ledger-avalanche/go v0.0.0-20231102202641-ae2ebdaeac34/go.mod h1:pJxaT9bUgeRNVmNRgtCHb7sFDIRKy7CzTQVi8gGNT6g= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= @@ -103,6 +103,7 @@ github.com/cenkalti/backoff/v4 v4.1.3 h1:cFAlzYUlVYDysBEH2T5hyJZMh3+5+WCBvSnK6Q8 github.com/cenkalti/backoff/v4 v4.1.3/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/cp v0.1.0 h1:SE+dxFebS7Iik5LK0tsi1k9ZCxEaFX4AjQmoyA+1dJk= +github.com/cespare/cp v0.1.0/go.mod h1:SOGHArjBr4JWaSDEVpWpo/hNg6RoKrls6Oh40hiwW+s= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= @@ -210,6 +211,7 @@ github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/ github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= +github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= @@ -249,6 +251,7 @@ github.com/golang-jwt/jwt/v4 v4.3.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzw github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/glog v1.1.0 h1:/d3pCKDPWNnvIWe0vVUpNP32qc8U3PDVxySP/y360qE= +github.com/golang/glog v1.1.0/go.mod h1:pfYeQZ3JWZoXTV5sFc986z3HTpwQs9At6P4ImfuP3NQ= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -415,6 +418,7 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/labstack/echo/v4 v4.5.0/go.mod h1:czIriw4a0C1dFun+ObrXp7ok03xON0N1awStJ6ArI7Y= github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= github.com/leanovate/gopter v0.2.9 h1:fQjYxZaynp97ozCzfOyOuAGOU4aU/z37zf/tOujFk7c= @@ -733,6 +737,7 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0= +golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= diff --git a/indexer/index.go b/indexer/index.go index 86d75b37d4cb..16a127c9795b 100644 --- a/indexer/index.go +++ b/indexer/index.go @@ -17,7 +17,6 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/timer/mockable" ) @@ -222,7 +221,7 @@ func (i *index) GetContainerRange(startIndex, numToFetch uint64) ([]Container, e } // Calculate the last index we will fetch - lastIndex := math.Min(startIndex+numToFetch-1, lastAcceptedIndex) + lastIndex := min(startIndex+numToFetch-1, lastAcceptedIndex) // [lastIndex] is always >= [startIndex] so this is safe. // [numToFetch] is limited to [MaxFetchedByRange] so [containers] is bounded in size. containers := make([]Container, int(lastIndex)-int(startIndex)+1) diff --git a/message/messages.go b/message/messages.go index b8b5db69e958..9fd0598683f6 100644 --- a/message/messages.go +++ b/message/messages.go @@ -19,7 +19,6 @@ import ( "github.com/ava-labs/avalanchego/utils/compression" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/metric" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/wrappers" @@ -353,7 +352,7 @@ func (mb *msgBuilder) parseInbound( expiration := mockable.MaxTime if deadline, ok := GetDeadline(msg); ok { - deadline = math.Min(deadline, mb.maxMessageTimeout) + deadline = min(deadline, mb.maxMessageTimeout) expiration = time.Now().Add(deadline) } diff --git a/network/ip_tracker.go b/network/ip_tracker.go index 758c53494580..bdb494522d7e 100644 --- a/network/ip_tracker.go +++ b/network/ip_tracker.go @@ -11,8 +11,6 @@ import ( "go.uber.org/zap" - "golang.org/x/exp/maps" - "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils" @@ -20,7 +18,6 @@ import ( "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/ips" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/metric" "github.com/ava-labs/avalanchego/utils/sampler" "github.com/ava-labs/avalanchego/utils/set" @@ -382,7 +379,7 @@ func (i *ipTracker) resetBloom() error { return err } - count := math.Max(maxIPEntriesPerValidator*i.validators.Len(), minCountEstimate) + count := max(maxIPEntriesPerValidator*i.validators.Len(), minCountEstimate) numHashes, numEntries := bloom.OptimalParameters( count, targetFalsePositiveProbability, @@ -393,7 +390,7 @@ func (i *ipTracker) resetBloom() error { } i.bloom = newFilter - maps.Clear(i.bloomAdditions) + clear(i.bloomAdditions) i.bloomSalt = newSalt i.maxBloomCount = bloom.EstimateCount(numHashes, numEntries, maxFalsePositiveProbability) diff --git a/network/p2p/gossip/bloom.go b/network/p2p/gossip/bloom.go index 14d7ece6db85..e1a2e4d51d7f 100644 --- a/network/p2p/gossip/bloom.go +++ b/network/p2p/gossip/bloom.go @@ -10,7 +10,6 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/bloom" - "github.com/ava-labs/avalanchego/utils/math" ) // NewBloomFilter returns a new instance of a bloom filter with at least [minTargetElements] elements @@ -94,7 +93,7 @@ func ResetBloomFilterIfNeeded( return false, nil } - targetElements = math.Max(bloomFilter.minTargetElements, targetElements) + targetElements = max(bloomFilter.minTargetElements, targetElements) err := resetBloomFilter( bloomFilter, targetElements, diff --git a/network/p2p/gossip/bloom_test.go b/network/p2p/gossip/bloom_test.go index 00f75165b467..e6e2e85db80b 100644 --- a/network/p2p/gossip/bloom_test.go +++ b/network/p2p/gossip/bloom_test.go @@ -4,12 +4,11 @@ package gossip import ( + "slices" "testing" "github.com/stretchr/testify/require" - "golang.org/x/exp/slices" - "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/testutil" diff --git a/network/p2p/gossip/gossip_test.go b/network/p2p/gossip/gossip_test.go index a58d98f8fe58..f52af1efc375 100644 --- a/network/p2p/gossip/gossip_test.go +++ b/network/p2p/gossip/gossip_test.go @@ -11,12 +11,12 @@ import ( "github.com/prometheus/client_golang/prometheus" + "github.com/stretchr/testify/require" + "golang.org/x/exp/maps" "google.golang.org/protobuf/proto" - "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/network/p2p" "github.com/ava-labs/avalanchego/proto/pb/sdk" diff --git a/network/p2p/network_test.go b/network/p2p/network_test.go index 40dc0ba54056..b75cb8e35d78 100644 --- a/network/p2p/network_test.go +++ b/network/p2p/network_test.go @@ -16,7 +16,6 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/version" ) @@ -478,7 +477,7 @@ func TestPeersSample(t *testing.T) { sampleable.Difference(tt.disconnected) sampled := network.Peers.Sample(tt.limit) - require.Len(sampled, math.Min(tt.limit, len(sampleable))) + require.Len(sampled, min(tt.limit, len(sampleable))) require.Subset(sampleable, sampled) }) } diff --git a/network/throttling/inbound_msg_byte_throttler.go b/network/throttling/inbound_msg_byte_throttler.go index 459df7a11b5d..163b9782ca1c 100644 --- a/network/throttling/inbound_msg_byte_throttler.go +++ b/network/throttling/inbound_msg_byte_throttler.go @@ -16,7 +16,6 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/linkedhashmap" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/metric" "github.com/ava-labs/avalanchego/utils/wrappers" ) @@ -108,7 +107,7 @@ func (t *inboundMsgByteThrottler) Acquire(ctx context.Context, msgSize uint64, n } // Take as many bytes as we can from the at-large allocation. - atLargeBytesUsed := math.Min( + atLargeBytesUsed := min( // only give as many bytes as needed metadata.bytesNeeded, // don't exceed per-node limit @@ -153,7 +152,7 @@ func (t *inboundMsgByteThrottler) Acquire(ctx context.Context, msgSize uint64, n } else { vdrBytesAllowed -= vdrBytesAlreadyUsed } - vdrBytesUsed := math.Min(t.remainingVdrBytes, metadata.bytesNeeded, vdrBytesAllowed) + vdrBytesUsed := min(t.remainingVdrBytes, metadata.bytesNeeded, vdrBytesAllowed) if vdrBytesUsed > 0 { // Mark that [nodeID] used [vdrBytesUsed] from its validator allocation t.nodeToVdrBytesUsed[nodeID] += vdrBytesUsed @@ -216,7 +215,7 @@ func (t *inboundMsgByteThrottler) release(metadata *msgMetadata, nodeID ids.Node // or messages from [nodeID] currently waiting to acquire bytes. vdrBytesUsed := t.nodeToVdrBytesUsed[nodeID] releasedBytes := metadata.msgSize - metadata.bytesNeeded - vdrBytesToReturn := math.Min(releasedBytes, vdrBytesUsed) + vdrBytesToReturn := min(releasedBytes, vdrBytesUsed) // [atLargeBytesToReturn] is the number of bytes from [msgSize] // that will be given to the at-large allocation or a message @@ -239,7 +238,7 @@ func (t *inboundMsgByteThrottler) release(metadata *msgMetadata, nodeID ids.Node msg := iter.Value() // From the at-large allocation, take the maximum number of bytes // without exceeding the per-node limit on taking from at-large pool. - atLargeBytesGiven := math.Min( + atLargeBytesGiven := min( // don't give [msg] too many bytes msg.bytesNeeded, // don't exceed per-node limit @@ -272,7 +271,7 @@ func (t *inboundMsgByteThrottler) release(metadata *msgMetadata, nodeID ids.Node msg, exists := t.waitingToAcquire.Get(msgID) if exists { // Give [msg] all the bytes we can - bytesToGive := math.Min(msg.bytesNeeded, vdrBytesToReturn) + bytesToGive := min(msg.bytesNeeded, vdrBytesToReturn) msg.bytesNeeded -= bytesToGive vdrBytesToReturn -= bytesToGive if msg.bytesNeeded == 0 { diff --git a/network/throttling/outbound_msg_throttler.go b/network/throttling/outbound_msg_throttler.go index e1656c04ffe1..b2d75b0483f2 100644 --- a/network/throttling/outbound_msg_throttler.go +++ b/network/throttling/outbound_msg_throttler.go @@ -14,7 +14,6 @@ import ( "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/utils/math" ) var ( @@ -75,7 +74,7 @@ func (t *outboundMsgThrottler) Acquire(msg message.OutboundMessage, nodeID ids.N // Take as many bytes as we can from the at-large allocation. bytesNeeded := uint64(len(msg.Bytes())) - atLargeBytesUsed := math.Min( + atLargeBytesUsed := min( // only give as many bytes as needed bytesNeeded, // don't exceed per-node limit @@ -109,7 +108,7 @@ func (t *outboundMsgThrottler) Acquire(msg message.OutboundMessage, nodeID ids.N } else { vdrBytesAllowed -= vdrBytesAlreadyUsed } - vdrBytesUsed := math.Min(t.remainingVdrBytes, bytesNeeded, vdrBytesAllowed) + vdrBytesUsed := min(t.remainingVdrBytes, bytesNeeded, vdrBytesAllowed) bytesNeeded -= vdrBytesUsed if bytesNeeded != 0 { // Can't acquire enough bytes to queue this message to be sent @@ -152,7 +151,7 @@ func (t *outboundMsgThrottler) Release(msg message.OutboundMessage, nodeID ids.N // that will be given back to [nodeID]'s validator allocation. vdrBytesUsed := t.nodeToVdrBytesUsed[nodeID] msgSize := uint64(len(msg.Bytes())) - vdrBytesToReturn := math.Min(msgSize, vdrBytesUsed) + vdrBytesToReturn := min(msgSize, vdrBytesUsed) t.nodeToVdrBytesUsed[nodeID] -= vdrBytesToReturn if t.nodeToVdrBytesUsed[nodeID] == 0 { delete(t.nodeToVdrBytesUsed, nodeID) diff --git a/proto/Dockerfile.buf b/proto/Dockerfile.buf index 3c8864e636b7..0a54f4a1e628 100644 --- a/proto/Dockerfile.buf +++ b/proto/Dockerfile.buf @@ -6,7 +6,7 @@ RUN apt-get update && apt -y install bash curl unzip git WORKDIR /opt RUN \ - curl -L https://golang.org/dl/go1.20.12.linux-amd64.tar.gz > golang.tar.gz && \ + curl -L https://go.dev/dl/go1.21.7.linux-amd64.tar.gz > golang.tar.gz && \ mkdir golang && \ tar -zxvf golang.tar.gz -C golang/ diff --git a/scripts/build_avalanche.sh b/scripts/build_avalanche.sh index dcfaed4c420d..eda63a5b959b 100755 --- a/scripts/build_avalanche.sh +++ b/scripts/build_avalanche.sh @@ -27,7 +27,7 @@ done # Dockerfile # README.md # go.mod -go_version_minimum="1.20.12" +go_version_minimum="1.21.7" go_version() { go version | sed -nE -e 's/[^0-9.]+([0-9.]+).+/\1/p' diff --git a/snow/consensus/snowball/network_test.go b/snow/consensus/snowball/network_test.go index 56e7d0ca7dbc..10448662a30a 100644 --- a/snow/consensus/snowball/network_test.go +++ b/snow/consensus/snowball/network_test.go @@ -6,7 +6,6 @@ package snowball import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/bag" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/sampler" ) @@ -88,7 +87,7 @@ func (n *Network) Round() { running := n.running[runningInd] s.Initialize(uint64(len(n.nodes))) - count := math.Min(n.params.K, len(n.nodes)) + count := min(n.params.K, len(n.nodes)) indices, _ := s.Sample(count) sampledColors := bag.Bag[ids.ID]{} for _, index := range indices { diff --git a/snow/consensus/snowman/bootstrapper/requests.go b/snow/consensus/snowman/bootstrapper/requests.go index ebeaf57ac70f..c152d6aacab8 100644 --- a/snow/consensus/snowman/bootstrapper/requests.go +++ b/snow/consensus/snowman/bootstrapper/requests.go @@ -7,7 +7,6 @@ import ( "context" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/set" ) @@ -24,7 +23,7 @@ func (r *requests) GetPeers(context.Context) set.Set[ids.NodeID] { return nil } - numToSend := math.Min( + numToSend := min( r.maxOutstanding-numPending, r.pendingSend.Len(), ) diff --git a/snow/consensus/snowman/bootstrapper/sampler.go b/snow/consensus/snowman/bootstrapper/sampler.go index e23253864669..b43f6d915745 100644 --- a/snow/consensus/snowman/bootstrapper/sampler.go +++ b/snow/consensus/snowman/bootstrapper/sampler.go @@ -35,7 +35,7 @@ func Sample[T comparable](elements map[T]uint64, maxSize int) (set.Set[T], error return nil, err } - maxSize = int(math.Min(uint64(maxSize), totalWeight)) + maxSize = int(min(uint64(maxSize), totalWeight)) indices, err := sampler.Sample(maxSize) if err != nil { return nil, err diff --git a/snow/consensus/snowman/metrics.go b/snow/consensus/snowman/metrics.go index a052db5144d4..4e527376df6d 100644 --- a/snow/consensus/snowman/metrics.go +++ b/snow/consensus/snowman/metrics.go @@ -14,7 +14,6 @@ import ( "github.com/ava-labs/avalanchego/snow/choices" "github.com/ava-labs/avalanchego/utils/linkedhashmap" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/metric" "github.com/ava-labs/avalanchego/utils/wrappers" ) @@ -199,7 +198,7 @@ func (m *metrics) Issued(blkID ids.ID, pollNumber uint64) { } func (m *metrics) Verified(height uint64) { - m.currentMaxVerifiedHeight = math.Max(m.currentMaxVerifiedHeight, height) + m.currentMaxVerifiedHeight = max(m.currentMaxVerifiedHeight, height) m.maxVerifiedHeight.Set(float64(m.currentMaxVerifiedHeight)) } diff --git a/snow/consensus/snowman/test_block.go b/snow/consensus/snowman/test_block.go index b59eb2ed5f89..a32872adbb96 100644 --- a/snow/consensus/snowman/test_block.go +++ b/snow/consensus/snowman/test_block.go @@ -4,6 +4,7 @@ package snowman import ( + "cmp" "context" "time" @@ -49,5 +50,5 @@ func (b *TestBlock) Bytes() []byte { } func (b *TestBlock) Compare(other *TestBlock) int { - return utils.Compare(b.HeightV, other.HeightV) + return cmp.Compare(b.HeightV, other.HeightV) } diff --git a/snow/consensus/snowman/topological.go b/snow/consensus/snowman/topological.go index 5b12ce3f2e6b..d99ac9c293ad 100644 --- a/snow/consensus/snowman/topological.go +++ b/snow/consensus/snowman/topological.go @@ -11,8 +11,6 @@ import ( "go.uber.org/zap" - "golang.org/x/exp/maps" - "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/choices" @@ -305,7 +303,7 @@ func (ts *Topological) RecordPoll(ctx context.Context, voteBag bag.Bag[ids.ID]) // Runtime = 2 * |live set| ; Space = Constant ts.preferredIDs.Clear() - maps.Clear(ts.preferredHeights) + clear(ts.preferredHeights) ts.preference = preferred startBlock := ts.blocks[ts.preference] @@ -369,7 +367,7 @@ func (ts *Topological) HealthCheck(context.Context) (interface{}, error) { // the non-transitively applied votes. Also returns the list of leaf blocks. func (ts *Topological) calculateInDegree(votes bag.Bag[ids.ID]) { // Clear the Kahn node set - maps.Clear(ts.kahnNodes) + clear(ts.kahnNodes) // Clear the leaf set ts.leaves.Clear() diff --git a/snow/engine/avalanche/bootstrap/bootstrapper_test.go b/snow/engine/avalanche/bootstrap/bootstrapper_test.go index 7da0b99a8736..133e90519b66 100644 --- a/snow/engine/avalanche/bootstrap/bootstrapper_test.go +++ b/snow/engine/avalanche/bootstrap/bootstrapper_test.go @@ -12,8 +12,6 @@ import ( "github.com/stretchr/testify/require" - "golang.org/x/exp/maps" - "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/ids" @@ -711,7 +709,7 @@ func TestBootstrapperUnexpectedVertex(t *testing.T) { require.Contains(requestIDs, vtxID1) reqID := requestIDs[vtxID1] - maps.Clear(requestIDs) + clear(requestIDs) require.NoError(bs.Ancestors(context.Background(), peerID, reqID, [][]byte{vtxBytes0})) require.Contains(requestIDs, vtxID1) diff --git a/snow/engine/avalanche/state/serializer.go b/snow/engine/avalanche/state/serializer.go index b305100b9ce2..be8cabc6e140 100644 --- a/snow/engine/avalanche/state/serializer.go +++ b/snow/engine/avalanche/state/serializer.go @@ -90,7 +90,7 @@ func (s *Serializer) BuildStopVtx( if err != nil { return nil, err } - height = math.Max(height, childHeight) + height = max(height, childHeight) } vtx, err := vertex.BuildStopVertex( diff --git a/snow/engine/snowman/syncer/config.go b/snow/engine/snowman/syncer/config.go index b5fae133a376..8adb1e6d4c2a 100644 --- a/snow/engine/snowman/syncer/config.go +++ b/snow/engine/snowman/syncer/config.go @@ -12,7 +12,6 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/common/tracker" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "github.com/ava-labs/avalanchego/snow/validators" - "github.com/ava-labs/avalanchego/utils/math" ) type Config struct { @@ -67,7 +66,7 @@ func NewConfig( if err != nil { return Config{}, fmt.Errorf("failed to calculate total weight of state sync beacons for subnet %s: %w", ctx.SubnetID, err) } - sampleK = int(math.Min(uint64(sampleK), stateSyncingWeight)) + sampleK = int(min(uint64(sampleK), stateSyncingWeight)) alpha = stateSyncingWeight/2 + 1 // must be > 50% } return Config{ diff --git a/snow/engine/snowman/syncer/state_syncer_test.go b/snow/engine/snowman/syncer/state_syncer_test.go index 11faeae69f67..1046e1fdd4cf 100644 --- a/snow/engine/snowman/syncer/state_syncer_test.go +++ b/snow/engine/snowman/syncer/state_syncer_test.go @@ -25,8 +25,6 @@ import ( "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/version" - - safemath "github.com/ava-labs/avalanchego/utils/math" ) var ( @@ -248,7 +246,7 @@ func TestBeaconsAreReachedForFrontiersUponStartup(t *testing.T) { } // check that vdrs are reached out for frontiers - require.Len(contactedFrontiersProviders, safemath.Min(beacons.Count(ctx.SubnetID), maxOutstandingBroadcastRequests)) + require.Len(contactedFrontiersProviders, min(beacons.Count(ctx.SubnetID), maxOutstandingBroadcastRequests)) for beaconID := range contactedFrontiersProviders { // check that beacon is duly marked as reached out require.Contains(syncer.pendingSeeders, beaconID) diff --git a/snow/networking/handler/handler.go b/snow/networking/handler/handler.go index 35dc40f57f98..950cc0f84d8c 100644 --- a/snow/networking/handler/handler.go +++ b/snow/networking/handler/handler.go @@ -29,7 +29,6 @@ import ( "github.com/ava-labs/avalanchego/snow/networking/tracker" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/subnets" - "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/timer/mockable" @@ -241,7 +240,7 @@ func (h *handler) Start(ctx context.Context, recoverPanic bool) { return } - detachedCtx := utils.Detach(ctx) + detachedCtx := context.WithoutCancel(ctx) dispatchSync := func() { h.dispatchSync(detachedCtx) } diff --git a/snow/networking/sender/sender.go b/snow/networking/sender/sender.go index 08a05305029a..648a01a2ce77 100644 --- a/snow/networking/sender/sender.go +++ b/snow/networking/sender/sender.go @@ -19,7 +19,6 @@ import ( "github.com/ava-labs/avalanchego/snow/networking/router" "github.com/ava-labs/avalanchego/snow/networking/timeout" "github.com/ava-labs/avalanchego/subnets" - "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" @@ -94,7 +93,7 @@ func New( } func (s *sender) SendGetStateSummaryFrontier(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // Note that this timeout duration won't exactly match the one that gets // registered. That's OK. @@ -175,7 +174,7 @@ func (s *sender) SendGetStateSummaryFrontier(ctx context.Context, nodeIDs set.Se } func (s *sender) SendStateSummaryFrontier(ctx context.Context, nodeID ids.NodeID, requestID uint32, summary []byte) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // Sending this message to myself. if nodeID == s.ctx.NodeID { @@ -235,7 +234,7 @@ func (s *sender) SendStateSummaryFrontier(ctx context.Context, nodeID ids.NodeID } func (s *sender) SendGetAcceptedStateSummary(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, heights []uint64) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // Note that this timeout duration won't exactly match the one that gets // registered. That's OK. @@ -319,7 +318,7 @@ func (s *sender) SendGetAcceptedStateSummary(ctx context.Context, nodeIDs set.Se } func (s *sender) SendAcceptedStateSummary(ctx context.Context, nodeID ids.NodeID, requestID uint32, summaryIDs []ids.ID) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) if nodeID == s.ctx.NodeID { inMsg := message.InboundAcceptedStateSummary( @@ -369,7 +368,7 @@ func (s *sender) SendAcceptedStateSummary(ctx context.Context, nodeID ids.NodeID } func (s *sender) SendGetAcceptedFrontier(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // Note that this timeout duration won't exactly match the one that gets // registered. That's OK. @@ -453,7 +452,7 @@ func (s *sender) SendGetAcceptedFrontier(ctx context.Context, nodeIDs set.Set[id } func (s *sender) SendAcceptedFrontier(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerID ids.ID) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // Sending this message to myself. if nodeID == s.ctx.NodeID { @@ -504,7 +503,7 @@ func (s *sender) SendAcceptedFrontier(ctx context.Context, nodeID ids.NodeID, re } func (s *sender) SendGetAccepted(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, containerIDs []ids.ID) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // Note that this timeout duration won't exactly match the one that gets // registered. That's OK. @@ -591,7 +590,7 @@ func (s *sender) SendGetAccepted(ctx context.Context, nodeIDs set.Set[ids.NodeID } func (s *sender) SendAccepted(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerIDs []ids.ID) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) if nodeID == s.ctx.NodeID { inMsg := message.InboundAccepted( @@ -637,7 +636,7 @@ func (s *sender) SendAccepted(ctx context.Context, nodeID ids.NodeID, requestID } func (s *sender) SendGetAncestors(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerID ids.ID) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // Tell the router to expect a response message or a message notifying // that we won't get a response from this node. @@ -753,7 +752,7 @@ func (s *sender) SendAncestors(_ context.Context, nodeID ids.NodeID, requestID u } func (s *sender) SendGet(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerID ids.ID) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // Tell the router to expect a response message or a message notifying // that we won't get a response from this node. @@ -885,7 +884,7 @@ func (s *sender) SendPushQuery( container []byte, requestedHeight uint64, ) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // Tell the router to expect a response message or a message notifying // that we won't get a response from each of these nodes. @@ -1024,7 +1023,7 @@ func (s *sender) SendPullQuery( containerID ids.ID, requestedHeight uint64, ) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // Tell the router to expect a response message or a message notifying // that we won't get a response from each of these nodes. @@ -1153,7 +1152,7 @@ func (s *sender) SendChits( preferredIDAtHeight ids.ID, acceptedID ids.ID, ) { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // If [nodeID] is myself, send this message directly // to my own router rather than sending it over the network @@ -1207,7 +1206,7 @@ func (s *sender) SendChits( } func (s *sender) SendCrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, appRequestBytes []byte) error { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // The failed message is treated as if it was sent by the requested chain failedMsg := message.InternalCrossChainAppError( @@ -1242,7 +1241,7 @@ func (s *sender) SendCrossChainAppRequest(ctx context.Context, chainID ids.ID, r } func (s *sender) SendCrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, appResponseBytes []byte) error { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) inMsg := message.InternalCrossChainAppResponse( s.ctx.NodeID, @@ -1256,7 +1255,7 @@ func (s *sender) SendCrossChainAppResponse(ctx context.Context, chainID ids.ID, } func (s *sender) SendAppRequest(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, appRequestBytes []byte) error { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) // Tell the router to expect a response message or a message notifying // that we won't get a response from each of these nodes. @@ -1386,7 +1385,7 @@ func (s *sender) SendAppRequest(ctx context.Context, nodeIDs set.Set[ids.NodeID] } func (s *sender) SendAppResponse(ctx context.Context, nodeID ids.NodeID, requestID uint32, appResponseBytes []byte) error { - ctx = utils.Detach(ctx) + ctx = context.WithoutCancel(ctx) if nodeID == s.ctx.NodeID { inMsg := message.InboundAppResponse( diff --git a/snow/networking/tracker/targeter.go b/snow/networking/tracker/targeter.go index 39a7398e391c..b52d8048effc 100644 --- a/snow/networking/tracker/targeter.go +++ b/snow/networking/tracker/targeter.go @@ -4,8 +4,6 @@ package tracker import ( - "math" - "go.uber.org/zap" "github.com/ava-labs/avalanchego/ids" @@ -63,8 +61,8 @@ type targeter struct { func (t *targeter) TargetUsage(nodeID ids.NodeID) float64 { // This node's at-large allocation is min([remaining at large], [max at large for a given peer]) usage := t.tracker.TotalUsage() - baseAlloc := math.Max(0, t.maxNonVdrUsage-usage) - baseAlloc = math.Min(baseAlloc, t.maxNonVdrNodeUsage) + baseAlloc := max(0, t.maxNonVdrUsage-usage) + baseAlloc = min(baseAlloc, t.maxNonVdrNodeUsage) // This node gets a stake-weighted portion of the validator allocation. weight := t.vdrs.GetWeight(constants.PrimaryNetworkID, nodeID) diff --git a/utils/bag/unique_bag.go b/utils/bag/unique_bag.go index f5d679a5b816..d695b7999601 100644 --- a/utils/bag/unique_bag.go +++ b/utils/bag/unique_bag.go @@ -111,5 +111,5 @@ func (b *UniqueBag[_]) String() string { // Removes all key --> bitset pairs. func (b *UniqueBag[_]) Clear() { - maps.Clear(*b) + clear(*b) } diff --git a/utils/bloom/optimal.go b/utils/bloom/optimal.go index fc434ca57987..e5ec228db1c2 100644 --- a/utils/bloom/optimal.go +++ b/utils/bloom/optimal.go @@ -3,11 +3,7 @@ package bloom -import ( - "math" - - safemath "github.com/ava-labs/avalanchego/utils/math" -) +import "math" const ln2Squared = math.Ln2 * math.Ln2 @@ -44,7 +40,7 @@ func OptimalHashes(numEntries, count int) int { if numHashes >= maxHashes { return maxHashes } - return safemath.Max(int(numHashes), minHashes) + return max(int(numHashes), minHashes) } // OptimalEntries calculates the optimal number of entries to use when creating @@ -75,7 +71,7 @@ func OptimalEntries(count int, falsePositiveProbability float64) int { if entries >= math.MaxInt { return math.MaxInt } - return safemath.Max(int(entries), minEntries) + return max(int(entries), minEntries) } // EstimateCount estimates the number of additions a bloom filter with diff --git a/utils/context.go b/utils/context.go deleted file mode 100644 index 453c45e948a4..000000000000 --- a/utils/context.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package utils - -import ( - "context" - "time" -) - -type detachedContext struct { - ctx context.Context -} - -func Detach(ctx context.Context) context.Context { - return &detachedContext{ - ctx: ctx, - } -} - -func (*detachedContext) Deadline() (time.Time, bool) { - return time.Time{}, false -} - -func (*detachedContext) Done() <-chan struct{} { - return nil -} - -func (*detachedContext) Err() error { - return nil -} - -func (c *detachedContext) Value(key any) any { - return c.ctx.Value(key) -} diff --git a/utils/math/safe_math.go b/utils/math/safe_math.go index 8397327414a7..e975d0d3ecc4 100644 --- a/utils/math/safe_math.go +++ b/utils/math/safe_math.go @@ -17,24 +17,6 @@ var ( ErrUnderflow = errors.New("underflow") ) -func Max[T constraints.Ordered](max T, nums ...T) T { - for _, num := range nums { - if num > max { - max = num - } - } - return max -} - -func Min[T constraints.Ordered](min T, nums ...T) T { - for _, num := range nums { - if num < min { - min = num - } - } - return min -} - // Add64 returns: // 1) a + b // 2) If there is overflow, an error @@ -74,5 +56,5 @@ func Mul64(a, b uint64) (uint64, error) { } func AbsDiff[T constraints.Unsigned](a, b T) T { - return Max(a, b) - Min(a, b) + return max(a, b) - min(a, b) } diff --git a/utils/math/safe_math_test.go b/utils/math/safe_math_test.go index fc89d2f7f639..7bcd12a6371a 100644 --- a/utils/math/safe_math_test.go +++ b/utils/math/safe_math_test.go @@ -12,29 +12,6 @@ import ( const maxUint64 uint64 = math.MaxUint64 -func TestMax(t *testing.T) { - require := require.New(t) - - require.Equal(maxUint64, Max(0, maxUint64)) - require.Equal(maxUint64, Max(maxUint64, 0)) - require.Equal(1, Max(1, 0)) - require.Equal(1, Max(0, 1)) - require.Zero(Max(0, 0)) - require.Equal(2, Max(2, 2)) -} - -func TestMin(t *testing.T) { - require := require.New(t) - - require.Zero(Min(uint64(0), maxUint64)) - require.Zero(Min(maxUint64, uint64(0))) - require.Zero(Min(1, 0)) - require.Zero(Min(0, 1)) - require.Zero(Min(0, 0)) - require.Equal(2, Min(2, 2)) - require.Equal(1, Min(1, 2)) -} - func TestAdd64(t *testing.T) { require := require.New(t) diff --git a/utils/maybe/maybe_test.go b/utils/maybe/maybe_test.go index 93d5fc32e85a..f2a88f663636 100644 --- a/utils/maybe/maybe_test.go +++ b/utils/maybe/maybe_test.go @@ -4,10 +4,10 @@ package maybe import ( + "slices" "testing" "github.com/stretchr/testify/require" - "golang.org/x/exp/slices" ) func TestMaybeClone(t *testing.T) { diff --git a/utils/sampler/uniform_replacer.go b/utils/sampler/uniform_replacer.go index 98d3e5acbe0d..80666a238343 100644 --- a/utils/sampler/uniform_replacer.go +++ b/utils/sampler/uniform_replacer.go @@ -3,8 +3,6 @@ package sampler -import "golang.org/x/exp/maps" - type defaultMap map[uint64]uint64 func (m defaultMap) get(key uint64, defaultVal uint64) uint64 { @@ -53,7 +51,7 @@ func (s *uniformReplacer) Sample(count int) ([]uint64, error) { } func (s *uniformReplacer) Reset() { - maps.Clear(s.drawn) + clear(s.drawn) s.drawsCount = 0 } diff --git a/utils/sampler/uniform_resample.go b/utils/sampler/uniform_resample.go index 1e48d51fa421..b05ce62fe886 100644 --- a/utils/sampler/uniform_resample.go +++ b/utils/sampler/uniform_resample.go @@ -3,8 +3,6 @@ package sampler -import "golang.org/x/exp/maps" - // uniformResample allows for sampling over a uniform distribution without // replacement. // @@ -40,7 +38,7 @@ func (s *uniformResample) Sample(count int) ([]uint64, error) { } func (s *uniformResample) Reset() { - maps.Clear(s.drawn) + clear(s.drawn) } func (s *uniformResample) Next() (uint64, error) { diff --git a/utils/sampler/uniform_test.go b/utils/sampler/uniform_test.go index 451a26625424..eb9862e7656c 100644 --- a/utils/sampler/uniform_test.go +++ b/utils/sampler/uniform_test.go @@ -6,11 +6,10 @@ package sampler import ( "fmt" "math" + "slices" "testing" "github.com/stretchr/testify/require" - - "golang.org/x/exp/slices" ) var ( diff --git a/utils/sampler/weighted_array.go b/utils/sampler/weighted_array.go index e13788422b85..bbbf98914d68 100644 --- a/utils/sampler/weighted_array.go +++ b/utils/sampler/weighted_array.go @@ -4,6 +4,8 @@ package sampler import ( + "cmp" + "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/math" ) @@ -20,7 +22,7 @@ type weightedArrayElement struct { // Note that this sorts in order of decreasing weight. func (e weightedArrayElement) Compare(other weightedArrayElement) int { - return utils.Compare(other.cumulativeWeight, e.cumulativeWeight) + return cmp.Compare(other.cumulativeWeight, e.cumulativeWeight) } // Sampling is performed by executing a modified binary search over the provided diff --git a/utils/sampler/weighted_heap.go b/utils/sampler/weighted_heap.go index 866c23893fc2..f4002a857e4a 100644 --- a/utils/sampler/weighted_heap.go +++ b/utils/sampler/weighted_heap.go @@ -4,6 +4,8 @@ package sampler import ( + "cmp" + "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/math" ) @@ -25,10 +27,10 @@ func (e weightedHeapElement) Compare(other weightedHeapElement) int { // By accounting for the initial index of the weights, this results in a // stable sort. We do this rather than using `sort.Stable` because of the // reported change in performance of the sort used. - if weightCmp := utils.Compare(other.weight, e.weight); weightCmp != 0 { + if weightCmp := cmp.Compare(other.weight, e.weight); weightCmp != 0 { return weightCmp } - return utils.Compare(e.index, other.index) + return cmp.Compare(e.index, other.index) } // Sampling is performed by executing a search over a tree of elements in the diff --git a/utils/sampler/weighted_linear.go b/utils/sampler/weighted_linear.go index 496613aea6dc..d6f0c5d74fba 100644 --- a/utils/sampler/weighted_linear.go +++ b/utils/sampler/weighted_linear.go @@ -4,6 +4,8 @@ package sampler import ( + "cmp" + "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/math" ) @@ -20,7 +22,7 @@ type weightedLinearElement struct { // Note that this sorts in order of decreasing cumulative weight. func (e weightedLinearElement) Compare(other weightedLinearElement) int { - return utils.Compare(other.cumulativeWeight, e.cumulativeWeight) + return cmp.Compare(other.cumulativeWeight, e.cumulativeWeight) } // Sampling is performed by executing a linear search over the provided elements diff --git a/utils/sampler/weighted_without_replacement_test.go b/utils/sampler/weighted_without_replacement_test.go index 48952d5cac14..8d3469141da1 100644 --- a/utils/sampler/weighted_without_replacement_test.go +++ b/utils/sampler/weighted_without_replacement_test.go @@ -6,12 +6,11 @@ package sampler import ( "fmt" "math" + "slices" "testing" "github.com/stretchr/testify/require" - "golang.org/x/exp/slices" - safemath "github.com/ava-labs/avalanchego/utils/math" ) diff --git a/utils/set/sampleable_set.go b/utils/set/sampleable_set.go index becd228fac43..bbeb2ae80c26 100644 --- a/utils/set/sampleable_set.go +++ b/utils/set/sampleable_set.go @@ -5,15 +5,12 @@ package set import ( "bytes" + "slices" stdjson "encoding/json" - "golang.org/x/exp/maps" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/json" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/sampler" "github.com/ava-labs/avalanchego/utils/wrappers" ) @@ -110,7 +107,7 @@ func (s *SampleableSet[T]) Remove(elements ...T) { // Clear empties this set func (s *SampleableSet[T]) Clear() { - maps.Clear(s.indices) + clear(s.indices) for i := range s.elements { s.elements[i] = utils.Zero[T]() } @@ -142,7 +139,7 @@ func (s SampleableSet[T]) Sample(numToSample int) []T { uniform := sampler.NewUniform() uniform.Initialize(uint64(len(s.elements))) - indices, _ := uniform.Sample(math.Min(len(s.elements), numToSample)) + indices, _ := uniform.Sample(min(len(s.elements), numToSample)) elements := make([]T, len(indices)) for i, index := range indices { elements[i] = s.elements[index] diff --git a/utils/set/set.go b/utils/set/set.go index 84cb5d46cd95..95a87e783d2d 100644 --- a/utils/set/set.go +++ b/utils/set/set.go @@ -5,11 +5,11 @@ package set import ( "bytes" + "slices" stdjson "encoding/json" "golang.org/x/exp/maps" - "golang.org/x/exp/slices" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/json" @@ -111,7 +111,7 @@ func (s *Set[T]) Remove(elts ...T) { // Clear empties this set func (s *Set[_]) Clear() { - maps.Clear(*s) + clear(*s) } // List converts this set into a list diff --git a/utils/sorting.go b/utils/sorting.go index 070375811ee3..a9c900ab1137 100644 --- a/utils/sorting.go +++ b/utils/sorting.go @@ -5,9 +5,8 @@ package utils import ( "bytes" - - "golang.org/x/exp/constraints" - "golang.org/x/exp/slices" + "cmp" + "slices" "github.com/ava-labs/avalanchego/utils/hashing" ) @@ -53,7 +52,7 @@ func IsSortedAndUnique[T Sortable[T]](s []T) bool { } // Returns true iff the elements in [s] are unique and sorted. -func IsSortedAndUniqueOrdered[T constraints.Ordered](s []T) bool { +func IsSortedAndUniqueOrdered[T cmp.Ordered](s []T) bool { for i := 0; i < len(s)-1; i++ { if s[i] >= s[i+1] { return false @@ -78,21 +77,3 @@ func IsSortedAndUniqueByHash[T ~[]byte](s []T) bool { } return true } - -// Compare returns -// -// -1 if x is less than y, -// 0 if x equals y, -// 1 if x is greater than y. -// -// TODO: Remove after updating to go1.21. -func Compare[T constraints.Ordered](x, y T) int { - switch { - case x < y: - return -1 - case x > y: - return 1 - default: - return 0 - } -} diff --git a/utils/sorting_test.go b/utils/sorting_test.go index acab335034ed..247b1a39d0f0 100644 --- a/utils/sorting_test.go +++ b/utils/sorting_test.go @@ -4,6 +4,7 @@ package utils import ( + "cmp" "testing" "github.com/stretchr/testify/require" @@ -14,7 +15,7 @@ var _ Sortable[sortable] = sortable(0) type sortable int func (s sortable) Compare(other sortable) int { - return Compare(s, other) + return cmp.Compare(s, other) } func TestSortSliceSortable(t *testing.T) { diff --git a/vms/avm/genesis.go b/vms/avm/genesis.go index b2d6e7409152..a3ca5ca259f9 100644 --- a/vms/avm/genesis.go +++ b/vms/avm/genesis.go @@ -4,6 +4,8 @@ package avm import ( + "cmp" + "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/vms/avm/txs" ) @@ -20,5 +22,5 @@ type GenesisAsset struct { } func (g *GenesisAsset) Compare(other *GenesisAsset) int { - return utils.Compare(g.Alias, other.Alias) + return cmp.Compare(g.Alias, other.Alias) } diff --git a/vms/avm/state/state.go b/vms/avm/state/state.go index e85907d77a50..354eb0e734c6 100644 --- a/vms/avm/state/state.go +++ b/vms/avm/state/state.go @@ -28,8 +28,6 @@ import ( "github.com/ava-labs/avalanchego/vms/avm/block" "github.com/ava-labs/avalanchego/vms/avm/txs" "github.com/ava-labs/avalanchego/vms/components/avax" - - safemath "github.com/ava-labs/avalanchego/utils/math" ) const ( @@ -723,7 +721,7 @@ func (s *state) Prune(lock sync.Locker, log logging.Logger) error { // could take an extremely long period of time; which we should not // delay processing for. pruneDuration := now.Sub(lastCommit) - sleepDuration := safemath.Min( + sleepDuration := min( pruneCommitSleepMultiplier*pruneDuration, pruneCommitSleepCap, ) diff --git a/vms/avm/txs/initial_state.go b/vms/avm/txs/initial_state.go index a093ead5c6b2..63321e56eea2 100644 --- a/vms/avm/txs/initial_state.go +++ b/vms/avm/txs/initial_state.go @@ -5,6 +5,7 @@ package txs import ( "bytes" + "cmp" "errors" "sort" @@ -60,7 +61,7 @@ func (is *InitialState) Verify(c codec.Manager, numFxs int) error { } func (is *InitialState) Compare(other *InitialState) int { - return utils.Compare(is.FxIndex, other.FxIndex) + return cmp.Compare(is.FxIndex, other.FxIndex) } func (is *InitialState) Sort(c codec.Manager) { diff --git a/vms/components/avax/utxo_id.go b/vms/components/avax/utxo_id.go index fafc940444b5..5e8cf871ae50 100644 --- a/vms/components/avax/utxo_id.go +++ b/vms/components/avax/utxo_id.go @@ -5,6 +5,7 @@ package avax import ( "bytes" + "cmp" "errors" "fmt" "strconv" @@ -97,5 +98,5 @@ func (utxo *UTXOID) Compare(other *UTXOID) int { if txIDComp := bytes.Compare(utxoID[:], otherID[:]); txIDComp != 0 { return txIDComp } - return utils.Compare(utxoIndex, otherIndex) + return cmp.Compare(utxoIndex, otherIndex) } diff --git a/vms/platformvm/api/static_service.go b/vms/platformvm/api/static_service.go index bd6e32d250a1..7b3b5232281d 100644 --- a/vms/platformvm/api/static_service.go +++ b/vms/platformvm/api/static_service.go @@ -4,6 +4,7 @@ package api import ( + "cmp" "errors" "fmt" "net/http" @@ -51,10 +52,10 @@ type UTXO struct { // TODO can we define this on *UTXO? func (utxo UTXO) Compare(other UTXO) int { - if locktimeCmp := utils.Compare(utxo.Locktime, other.Locktime); locktimeCmp != 0 { + if locktimeCmp := cmp.Compare(utxo.Locktime, other.Locktime); locktimeCmp != 0 { return locktimeCmp } - if amountCmp := utils.Compare(utxo.Amount, other.Amount); amountCmp != 0 { + if amountCmp := cmp.Compare(utxo.Amount, other.Amount); amountCmp != 0 { return amountCmp } diff --git a/vms/platformvm/service.go b/vms/platformvm/service.go index 16e5b16844c6..a53c9d769270 100644 --- a/vms/platformvm/service.go +++ b/vms/platformvm/service.go @@ -7,6 +7,7 @@ import ( "context" "errors" "fmt" + "maps" "math" "net/http" "time" @@ -15,8 +16,6 @@ import ( "go.uber.org/zap" - "golang.org/x/exp/maps" - "github.com/ava-labs/avalanchego/api" "github.com/ava-labs/avalanchego/cache" "github.com/ava-labs/avalanchego/database" diff --git a/vms/platformvm/state/state.go b/vms/platformvm/state/state.go index 4ae66d03c575..21ebd038505d 100644 --- a/vms/platformvm/state/state.go +++ b/vms/platformvm/state/state.go @@ -2590,7 +2590,7 @@ func (s *state) PruneAndIndex(lock sync.Locker, log logging.Logger) error { // could take an extremely long period of time; which we should not // delay processing for. pruneDuration := now.Sub(lastCommit) - sleepDuration := safemath.Min( + sleepDuration := min( pruneCommitSleepMultiplier*pruneDuration, pruneCommitSleepCap, ) diff --git a/vms/platformvm/txs/executor/staker_tx_verification.go b/vms/platformvm/txs/executor/staker_tx_verification.go index ea9343f11058..4dd72f6bf42c 100644 --- a/vms/platformvm/txs/executor/staker_tx_verification.go +++ b/vms/platformvm/txs/executor/staker_tx_verification.go @@ -419,7 +419,7 @@ func verifyAddDelegatorTx( } if backend.Config.IsApricotPhase3Activated(currentTimestamp) { - maximumWeight = safemath.Min(maximumWeight, backend.Config.MaxValidatorStake) + maximumWeight = min(maximumWeight, backend.Config.MaxValidatorStake) } if !txs.BoundedBy( @@ -672,7 +672,7 @@ func verifyAddPermissionlessDelegatorTx( if err != nil { maximumWeight = math.MaxUint64 } - maximumWeight = safemath.Min(maximumWeight, delegatorRules.maxValidatorStake) + maximumWeight = min(maximumWeight, delegatorRules.maxValidatorStake) if !txs.BoundedBy( startTime, diff --git a/vms/platformvm/txs/executor/staker_tx_verification_helpers.go b/vms/platformvm/txs/executor/staker_tx_verification_helpers.go index 2fb875552b86..3a74cea28696 100644 --- a/vms/platformvm/txs/executor/staker_tx_verification_helpers.go +++ b/vms/platformvm/txs/executor/staker_tx_verification_helpers.go @@ -231,7 +231,7 @@ func GetMaxWeight( if !delegator.NextTime.Before(startTime) { // We have advanced time to be at the inside of the delegation // window. Make sure that the max weight is updated accordingly. - currentMax = math.Max(currentMax, currentWeight) + currentMax = max(currentMax, currentWeight) } var op func(uint64, uint64) (uint64, error) @@ -248,7 +248,7 @@ func GetMaxWeight( // Because we assume [startTime] < [endTime], we have advanced time to // be at the end of the delegation window. Make sure that the max weight is // updated accordingly. - return math.Max(currentMax, currentWeight), nil + return max(currentMax, currentWeight), nil } func GetTransformSubnetTx(chain state.Chain, subnetID ids.ID) (*txs.TransformSubnetTx, error) { diff --git a/vms/platformvm/utxo/handler.go b/vms/platformvm/utxo/handler.go index f22a76fd0b8f..6368d97c11c8 100644 --- a/vms/platformvm/utxo/handler.go +++ b/vms/platformvm/utxo/handler.go @@ -229,7 +229,7 @@ func (h *handler) Spend( remainingValue := in.Amount() // Stake any value that should be staked - amountToStake := math.Min( + amountToStake := min( amount-amountStaked, // Amount we still need to stake remainingValue, // Amount available to stake ) @@ -320,7 +320,7 @@ func (h *handler) Spend( remainingValue := in.Amount() // Burn any value that should be burned - amountToBurn := math.Min( + amountToBurn := min( fee-amountBurned, // Amount we still need to burn remainingValue, // Amount available to burn ) @@ -328,7 +328,7 @@ func (h *handler) Spend( remainingValue -= amountToBurn // Stake any value that should be staked - amountToStake := math.Min( + amountToStake := min( amount-amountStaked, // Amount we still need to stake remainingValue, // Amount available to stake ) diff --git a/vms/proposervm/batched_vm_test.go b/vms/proposervm/batched_vm_test.go index 27cdaba0493f..3564b0b85b8f 100644 --- a/vms/proposervm/batched_vm_test.go +++ b/vms/proposervm/batched_vm_test.go @@ -22,7 +22,6 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/timer/mockable" ) @@ -499,7 +498,7 @@ func TestGetAncestorsAtSnomanPlusPlusFork(t *testing.T) { return nil, nil // unknown blockID } - endIndex := math.Min(startIndex+maxBlocksNum, len(sortedBlocks)) + endIndex := min(startIndex+maxBlocksNum, len(sortedBlocks)) return sortedBlocks[startIndex:endIndex], nil } diff --git a/vms/proposervm/proposer/windower.go b/vms/proposervm/proposer/windower.go index 6d1d958dd04a..b9a633c702c0 100644 --- a/vms/proposervm/proposer/windower.go +++ b/vms/proposervm/proposer/windower.go @@ -131,7 +131,7 @@ func (w *windower) Proposers(ctx context.Context, blockHeight, pChainHeight uint source.Seed(w.chainSource ^ blockHeight) - numToSample := int(math.Min(uint64(maxWindows), totalWeight)) + numToSample := int(min(uint64(maxWindows), totalWeight)) indices, err := sampler.Sample(numToSample) if err != nil { return nil, err diff --git a/vms/proposervm/proposer/windower_test.go b/vms/proposervm/proposer/windower_test.go index d3e2ac68817a..3da08feec2a4 100644 --- a/vms/proposervm/proposer/windower_test.go +++ b/vms/proposervm/proposer/windower_test.go @@ -431,7 +431,7 @@ func TestProposerDistribution(t *testing.T) { maxDeviation uint64 ) for _, sampled := range proposerFrequency { - maxDeviation = safemath.Max( + maxDeviation = max( maxDeviation, safemath.AbsDiff( uint64(sampled), diff --git a/vms/proposervm/vm.go b/vms/proposervm/vm.go index 111c0922104c..3b1529afd66b 100644 --- a/vms/proposervm/vm.go +++ b/vms/proposervm/vm.go @@ -25,7 +25,6 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowman" "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" - "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/timer/mockable" @@ -192,7 +191,7 @@ func (vm *VM) Initialize( }) vm.verifiedBlocks = make(map[ids.ID]PostForkBlock) - detachedCtx := utils.Detach(ctx) + detachedCtx := context.WithoutCancel(ctx) context, cancel := context.WithCancel(detachedCtx) vm.context = context vm.onShutdown = cancel @@ -380,7 +379,7 @@ func (vm *VM) getPreDurangoSlotTime( // validators can specify. This delay may be an issue for high performance, // custom VMs. Until the P-chain is modified to target a specific block // time, ProposerMinBlockDelay can be configured in the subnet config. - delay = math.Max(delay, vm.MinBlkDelay) + delay = max(delay, vm.MinBlkDelay) return parentTimestamp.Add(delay), nil } @@ -406,7 +405,7 @@ func (vm *VM) getPostDurangoSlotTime( // time, ProposerMinBlockDelay can be configured in the subnet config. switch { case err == nil: - delay = math.Max(delay, vm.MinBlkDelay) + delay = max(delay, vm.MinBlkDelay) return parentTimestamp.Add(delay), err case errors.Is(err, proposer.ErrAnyoneCanPropose): return parentTimestamp.Add(vm.MinBlkDelay), err @@ -907,7 +906,7 @@ func (vm *VM) optimalPChainHeight(ctx context.Context, minPChainHeight uint64) ( return 0, err } - return math.Max(minimumHeight, minPChainHeight), nil + return max(minimumHeight, minPChainHeight), nil } // parseInnerBlock attempts to parse the provided bytes as an inner block. If diff --git a/vms/rpcchainvm/ghttp/gresponsewriter/writer_server.go b/vms/rpcchainvm/ghttp/gresponsewriter/writer_server.go index b73d24f21024..86dd996369fc 100644 --- a/vms/rpcchainvm/ghttp/gresponsewriter/writer_server.go +++ b/vms/rpcchainvm/ghttp/gresponsewriter/writer_server.go @@ -8,8 +8,6 @@ import ( "errors" "net/http" - "golang.org/x/exp/maps" - "google.golang.org/protobuf/types/known/emptypb" "github.com/ava-labs/avalanchego/vms/rpcchainvm/ghttp/gconn" @@ -48,7 +46,7 @@ func (s *Server) Write( req *responsewriterpb.WriteRequest, ) (*responsewriterpb.WriteResponse, error) { headers := s.writer.Header() - maps.Clear(headers) + clear(headers) for _, header := range req.Headers { headers[header.Key] = header.Values } @@ -67,7 +65,7 @@ func (s *Server) WriteHeader( req *responsewriterpb.WriteHeaderRequest, ) (*emptypb.Empty, error) { headers := s.writer.Header() - maps.Clear(headers) + clear(headers) for _, header := range req.Headers { headers[header.Key] = header.Values } diff --git a/vms/rpcchainvm/vm_test.go b/vms/rpcchainvm/vm_test.go index b21cd503a74a..a1be92c62f4c 100644 --- a/vms/rpcchainvm/vm_test.go +++ b/vms/rpcchainvm/vm_test.go @@ -9,6 +9,7 @@ import ( "os" "os/exec" "reflect" + "slices" "testing" "time" @@ -16,8 +17,6 @@ import ( "go.uber.org/mock/gomock" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/vms/rpcchainvm/grpcutils" diff --git a/wallet/chain/c/builder.go b/wallet/chain/c/builder.go index 3e387ba3c27b..76482411938f 100644 --- a/wallet/chain/c/builder.go +++ b/wallet/chain/c/builder.go @@ -362,7 +362,7 @@ func (b *builder) NewExportTx( return nil, err } - inputAmount := math.Min(amountToConsume, avaxBalance) + inputAmount := min(amountToConsume, avaxBalance) inputs = append(inputs, evm.EVMInput{ Address: addr, Amount: inputAmount, diff --git a/wallet/chain/p/builder.go b/wallet/chain/p/builder.go index a2c7208ffe8a..ce6b5b05721c 100644 --- a/wallet/chain/p/builder.go +++ b/wallet/chain/p/builder.go @@ -1006,7 +1006,7 @@ func (b *builder) spend( }) // Stake any value that should be staked - amountToStake := math.Min( + amountToStake := min( remainingAmountToStake, // Amount we still need to stake out.Amt, // Amount available to stake ) @@ -1084,7 +1084,7 @@ func (b *builder) spend( }) // Burn any value that should be burned - amountToBurn := math.Min( + amountToBurn := min( remainingAmountToBurn, // Amount we still need to burn out.Amt, // Amount available to burn ) @@ -1092,7 +1092,7 @@ func (b *builder) spend( amountAvalibleToStake := out.Amt - amountToBurn // Burn any value that should be burned - amountToStake := math.Min( + amountToStake := min( remainingAmountToStake, // Amount we still need to stake amountAvalibleToStake, // Amount available to stake ) diff --git a/wallet/chain/x/builder.go b/wallet/chain/x/builder.go index 27932019e1f4..10c994c0a7f0 100644 --- a/wallet/chain/x/builder.go +++ b/wallet/chain/x/builder.go @@ -601,7 +601,7 @@ func (b *builder) spend( }) // Burn any value that should be burned - amountToBurn := math.Min( + amountToBurn := min( remainingAmountToBurn, // Amount we still need to burn out.Amt, // Amount available to burn ) diff --git a/x/archivedb/key_test.go b/x/archivedb/key_test.go index e5ea0ff3ced3..5c7ff9d08def 100644 --- a/x/archivedb/key_test.go +++ b/x/archivedb/key_test.go @@ -5,11 +5,10 @@ package archivedb import ( "bytes" + "slices" "testing" "github.com/stretchr/testify/require" - - "golang.org/x/exp/slices" ) func TestNaturalDescSortingForSameKey(t *testing.T) { diff --git a/x/merkledb/codec.go b/x/merkledb/codec.go index eae205631192..a5d4a922b0d9 100644 --- a/x/merkledb/codec.go +++ b/x/merkledb/codec.go @@ -10,10 +10,10 @@ import ( "io" "math" "math/bits" + "slices" "sync" "golang.org/x/exp/maps" - "golang.org/x/exp/slices" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/maybe" diff --git a/x/merkledb/db.go b/x/merkledb/db.go index 021ebc12d7d8..a9df2ced7f5b 100644 --- a/x/merkledb/db.go +++ b/x/merkledb/db.go @@ -9,12 +9,12 @@ import ( "errors" "fmt" "runtime" + "slices" "sync" "github.com/prometheus/client_golang/prometheus" "golang.org/x/exp/maps" - "golang.org/x/exp/slices" "golang.org/x/sync/semaphore" "go.opentelemetry.io/otel/attribute" @@ -25,7 +25,6 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/trace" "github.com/ava-labs/avalanchego/utils" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/maybe" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/units" @@ -329,7 +328,7 @@ func (db *merkleDB) rebuild(ctx context.Context, cacheSize int) error { } // Add all key-value pairs back into the database. - opsSizeLimit := math.Max( + opsSizeLimit := max( cacheSize/rebuildViewSizeFractionOfCacheSize, minRebuildViewSizePerCommit, ) diff --git a/x/merkledb/db_test.go b/x/merkledb/db_test.go index 48703556b72a..a950ebb587aa 100644 --- a/x/merkledb/db_test.go +++ b/x/merkledb/db_test.go @@ -8,6 +8,7 @@ import ( "context" "fmt" "math/rand" + "slices" "strconv" "testing" "time" @@ -16,9 +17,6 @@ import ( "github.com/stretchr/testify/require" - "golang.org/x/exp/maps" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" @@ -1019,7 +1017,7 @@ func runRandDBTest(require *require.Assertions, r *rand.Rand, rt randTest, token for key, value := range uncommittedKeyValues { values[key] = value } - maps.Clear(uncommittedKeyValues) + clear(uncommittedKeyValues) for key := range uncommittedDeletes { delete(values, key) diff --git a/x/merkledb/key.go b/x/merkledb/key.go index dd9938f6aaf0..524c95bb2dae 100644 --- a/x/merkledb/key.go +++ b/x/merkledb/key.go @@ -4,15 +4,14 @@ package merkledb import ( + "cmp" "errors" "fmt" + "slices" "strings" "unsafe" "golang.org/x/exp/maps" - "golang.org/x/exp/slices" - - "github.com/ava-labs/avalanchego/utils" ) var ( @@ -175,10 +174,10 @@ func (k Key) Less(other Key) bool { } func (k Key) Compare(other Key) int { - if valueCmp := utils.Compare(k.value, other.value); valueCmp != 0 { + if valueCmp := cmp.Compare(k.value, other.value); valueCmp != 0 { return valueCmp } - return utils.Compare(k.length, other.length) + return cmp.Compare(k.length, other.length) } // Extend returns a new Key that is the in-order aggregation of Key [k] with [keys] diff --git a/x/merkledb/node.go b/x/merkledb/node.go index 701e120e4b52..dd1f2ed65cd2 100644 --- a/x/merkledb/node.go +++ b/x/merkledb/node.go @@ -4,7 +4,7 @@ package merkledb import ( - "golang.org/x/exp/slices" + "slices" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/hashing" diff --git a/x/merkledb/trie.go b/x/merkledb/trie.go index bc2b4db81541..891a90d34e09 100644 --- a/x/merkledb/trie.go +++ b/x/merkledb/trie.go @@ -7,8 +7,7 @@ import ( "bytes" "context" "fmt" - - "golang.org/x/exp/slices" + "slices" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" diff --git a/x/merkledb/view.go b/x/merkledb/view.go index 8f9e688efc26..1583093d6617 100644 --- a/x/merkledb/view.go +++ b/x/merkledb/view.go @@ -6,14 +6,13 @@ package merkledb import ( "context" "errors" + "slices" "sync" "go.opentelemetry.io/otel/attribute" oteltrace "go.opentelemetry.io/otel/trace" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils" diff --git a/x/merkledb/view_iterator.go b/x/merkledb/view_iterator.go index 60d1b8909e76..14f1b3bd3a91 100644 --- a/x/merkledb/view_iterator.go +++ b/x/merkledb/view_iterator.go @@ -5,10 +5,9 @@ package merkledb import ( "bytes" + "slices" "github.com/ava-labs/avalanchego/database" - - "golang.org/x/exp/slices" ) func (v *view) NewIterator() database.Iterator { diff --git a/x/sync/manager.go b/x/sync/manager.go index 82f05eef08f9..e512b154feb2 100644 --- a/x/sync/manager.go +++ b/x/sync/manager.go @@ -8,12 +8,12 @@ import ( "context" "errors" "fmt" + "slices" "sync" - "golang.org/x/exp/maps" - "go.uber.org/zap" - "golang.org/x/exp/slices" + + "golang.org/x/exp/maps" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/logging" diff --git a/x/sync/network_server.go b/x/sync/network_server.go index f8c311964e05..ce49bffb2c8a 100644 --- a/x/sync/network_server.go +++ b/x/sync/network_server.go @@ -21,7 +21,6 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/hashing" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/maybe" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/x/merkledb" @@ -178,8 +177,8 @@ func (s *NetworkServer) HandleChangeProofRequest( // override limits if they exceed caps var ( - keyLimit = math.Min(req.KeyLimit, maxKeyValuesLimit) - bytesLimit = math.Min(int(req.BytesLimit), maxByteSizeLimit) + keyLimit = min(req.KeyLimit, maxKeyValuesLimit) + bytesLimit = min(int(req.BytesLimit), maxByteSizeLimit) start = maybeBytesToMaybe(req.StartKey) end = maybeBytesToMaybe(req.EndKey) ) @@ -295,8 +294,8 @@ func (s *NetworkServer) HandleRangeProofRequest( } // override limits if they exceed caps - req.KeyLimit = math.Min(req.KeyLimit, maxKeyValuesLimit) - req.BytesLimit = math.Min(req.BytesLimit, maxByteSizeLimit) + req.KeyLimit = min(req.KeyLimit, maxKeyValuesLimit) + req.BytesLimit = min(req.BytesLimit, maxByteSizeLimit) proofBytes, err := getRangeProof( ctx, diff --git a/x/sync/sync_test.go b/x/sync/sync_test.go index f77d4a30eecf..bc6cfb4f453c 100644 --- a/x/sync/sync_test.go +++ b/x/sync/sync_test.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "math/rand" + "slices" "testing" "time" @@ -14,8 +15,6 @@ import ( "go.uber.org/mock/gomock" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" diff --git a/x/sync/workheap.go b/x/sync/workheap.go index b49a19372caf..800aa39b3fe7 100644 --- a/x/sync/workheap.go +++ b/x/sync/workheap.go @@ -7,7 +7,6 @@ import ( "bytes" "github.com/ava-labs/avalanchego/utils/heap" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/maybe" "github.com/google/btree" @@ -106,7 +105,7 @@ func (wh *workHeap) MergeInsert(item *workItem) { // [beforeItem.start, beforeItem.end] and [item.start, item.end] are // merged into [beforeItem.start, item.end] beforeItem.end = item.end - beforeItem.priority = math.Max(item.priority, beforeItem.priority) + beforeItem.priority = max(item.priority, beforeItem.priority) wh.innerHeap.Fix(beforeItem) mergedBefore = beforeItem } @@ -123,7 +122,7 @@ func (wh *workHeap) MergeInsert(item *workItem) { // [item.start, item.end] and [afterItem.start, afterItem.end] are merged into // [item.start, afterItem.end]. afterItem.start = item.start - afterItem.priority = math.Max(item.priority, afterItem.priority) + afterItem.priority = max(item.priority, afterItem.priority) wh.innerHeap.Fix(afterItem) mergedAfter = afterItem } @@ -138,7 +137,7 @@ func (wh *workHeap) MergeInsert(item *workItem) { // remove the second range since it is now covered by the first wh.remove(mergedAfter) // update the priority - mergedBefore.priority = math.Max(mergedBefore.priority, mergedAfter.priority) + mergedBefore.priority = max(mergedBefore.priority, mergedAfter.priority) wh.innerHeap.Fix(mergedBefore) } diff --git a/x/sync/workheap_test.go b/x/sync/workheap_test.go index d073ce5f9fdc..41577f09f1c9 100644 --- a/x/sync/workheap_test.go +++ b/x/sync/workheap_test.go @@ -6,13 +6,12 @@ package sync import ( "bytes" "math/rand" + "slices" "testing" "time" "github.com/stretchr/testify/require" - "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/maybe" )