From 25fad00cb75680b8bf72b04b377365bb397e5224 Mon Sep 17 00:00:00 2001 From: dhrubabasu <7675102+dhrubabasu@users.noreply.github.com> Date: Wed, 11 Oct 2023 13:35:49 -0700 Subject: [PATCH 1/2] remove aliasing `math` standard lib --- .golangci.yml | 10 ++++ snow/engine/common/bootstrapper.go | 10 ++-- snow/engine/snowman/syncer/state_syncer.go | 10 ++-- .../snowman/syncer/state_syncer_test.go | 4 +- snow/validators/set_test.go | 20 ++++---- utils/sampler/weighted_test.go | 9 ++-- .../weighted_without_replacement_test.go | 9 ++-- vms/avm/states/state.go | 10 ++-- .../txs/executor/syntactic_verifier_test.go | 46 +++++++++---------- vms/platformvm/service.go | 36 +++++++-------- vms/platformvm/state/state.go | 20 ++++---- vms/platformvm/state/state_test.go | 14 +++--- .../add_permissionless_delegator_tx_test.go | 10 ++-- .../add_permissionless_validator_tx_test.go | 10 ++-- .../txs/executor/staker_tx_verification.go | 16 +++---- vms/platformvm/utxo/handler_test.go | 18 ++++---- x/sync/peer_tracker.go | 20 ++++---- 17 files changed, 140 insertions(+), 132 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 24f159fa8425..9f1dcc9c9389 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -58,6 +58,7 @@ linters: - gosec - gosimple - govet + - importas - ineffassign # - lll - misspell @@ -107,6 +108,15 @@ linters-settings: gosec: excludes: - G107 # Url provided to HTTP request as taint input https://securego.io/docs/rules/g107 + importas: + # Do not allow unaliased imports of aliased packages. + no-unaliased: false + # Do not allow non-required aliases. + no-extra-aliases: false + # List of aliases + alias: + - pkg: github.com/ava-labs/avalanchego/utils/math + alias: safemath revive: rules: # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#bool-literal-in-expr diff --git a/snow/engine/common/bootstrapper.go b/snow/engine/common/bootstrapper.go index c2ff101b1f7e..38543f228c74 100644 --- a/snow/engine/common/bootstrapper.go +++ b/snow/engine/common/bootstrapper.go @@ -5,15 +5,15 @@ package common import ( "context" - - stdmath "math" + "math" "go.uber.org/zap" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/set" + + safemath "github.com/ava-labs/avalanchego/utils/math" ) const ( @@ -195,14 +195,14 @@ func (b *bootstrapper) Accepted(ctx context.Context, nodeID ids.NodeID, requestI weight := b.Beacons.GetWeight(nodeID) for _, containerID := range containerIDs { previousWeight := b.acceptedVotes[containerID] - newWeight, err := math.Add64(weight, previousWeight) + newWeight, err := safemath.Add64(weight, previousWeight) if err != nil { b.Ctx.Log.Error("failed calculating the Accepted votes", zap.Uint64("weight", weight), zap.Uint64("previousWeight", previousWeight), zap.Error(err), ) - newWeight = stdmath.MaxUint64 + newWeight = math.MaxUint64 } b.acceptedVotes[containerID] = newWeight } diff --git a/snow/engine/snowman/syncer/state_syncer.go b/snow/engine/snowman/syncer/state_syncer.go index 1f7fc092a293..264b5a2b8d96 100644 --- a/snow/engine/snowman/syncer/state_syncer.go +++ b/snow/engine/snowman/syncer/state_syncer.go @@ -6,8 +6,7 @@ package syncer import ( "context" "fmt" - - stdmath "math" + "math" "go.uber.org/zap" @@ -19,9 +18,10 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "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" + + safemath "github.com/ava-labs/avalanchego/utils/math" ) var _ common.StateSyncer = (*stateSyncer)(nil) @@ -250,7 +250,7 @@ func (ss *stateSyncer) AcceptedStateSummary(ctx context.Context, nodeID ids.Node continue } - newWeight, err := math.Add64(nodeWeight, ws.weight) + newWeight, err := safemath.Add64(nodeWeight, ws.weight) if err != nil { ss.Ctx.Log.Error("failed to calculate new summary weight", zap.Stringer("nodeID", nodeID), @@ -260,7 +260,7 @@ func (ss *stateSyncer) AcceptedStateSummary(ctx context.Context, nodeID ids.Node zap.Uint64("previousWeight", ws.weight), zap.Error(err), ) - newWeight = stdmath.MaxUint64 + newWeight = math.MaxUint64 } ss.Ctx.Log.Verbo("updating summary weight", diff --git a/snow/engine/snowman/syncer/state_syncer_test.go b/snow/engine/snowman/syncer/state_syncer_test.go index be0eda96deba..26401e625385 100644 --- a/snow/engine/snowman/syncer/state_syncer_test.go +++ b/snow/engine/snowman/syncer/state_syncer_test.go @@ -22,7 +22,7 @@ import ( "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/version" - safeMath "github.com/ava-labs/avalanchego/utils/math" + safemath "github.com/ava-labs/avalanchego/utils/math" ) var ( @@ -251,7 +251,7 @@ func TestBeaconsAreReachedForFrontiersUponStartup(t *testing.T) { } // check that vdrs are reached out for frontiers - require.Len(contactedFrontiersProviders, safeMath.Min(vdrs.Len(), common.MaxOutstandingBroadcastRequests)) + require.Len(contactedFrontiersProviders, safemath.Min(vdrs.Len(), common.MaxOutstandingBroadcastRequests)) for beaconID := range contactedFrontiersProviders { // check that beacon is duly marked as reached out require.Contains(syncer.pendingSeeders, beaconID) diff --git a/snow/validators/set_test.go b/snow/validators/set_test.go index 44eecde1d4cf..673f8d6531b1 100644 --- a/snow/validators/set_test.go +++ b/snow/validators/set_test.go @@ -4,17 +4,17 @@ package validators import ( + "math" "testing" - stdmath "math" - "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/crypto/bls" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/sampler" "github.com/ava-labs/avalanchego/utils/set" + + safemath "github.com/ava-labs/avalanchego/utils/math" ) func TestSetAddZeroWeight(t *testing.T) { @@ -43,8 +43,8 @@ func TestSetAddOverflow(t *testing.T) { s := NewSet() require.NoError(s.Add(ids.GenerateTestNodeID(), nil, ids.Empty, 1)) - err := s.Add(ids.GenerateTestNodeID(), nil, ids.Empty, stdmath.MaxUint64) - require.ErrorIs(err, math.ErrOverflow) + err := s.Add(ids.GenerateTestNodeID(), nil, ids.Empty, math.MaxUint64) + require.ErrorIs(err, safemath.ErrOverflow) require.Equal(uint64(1), s.Weight()) } @@ -71,8 +71,8 @@ func TestSetAddWeightOverflow(t *testing.T) { nodeID := ids.GenerateTestNodeID() require.NoError(s.Add(nodeID, nil, ids.Empty, 1)) - err := s.AddWeight(nodeID, stdmath.MaxUint64-1) - require.ErrorIs(err, math.ErrOverflow) + err := s.AddWeight(nodeID, math.MaxUint64-1) + require.ErrorIs(err, safemath.ErrOverflow) require.Equal(uint64(2), s.Weight()) } @@ -150,7 +150,7 @@ func TestSetRemoveWeightUnderflow(t *testing.T) { require.NoError(s.Add(nodeID, nil, ids.Empty, 1)) err := s.RemoveWeight(nodeID, 2) - require.ErrorIs(err, math.ErrUnderflow) + require.ErrorIs(err, safemath.ErrUnderflow) require.Equal(uint64(2), s.Weight()) } @@ -354,7 +354,7 @@ func TestSetSample(t *testing.T) { require.ErrorIs(err, sampler.ErrOutOfRange) nodeID1 := ids.GenerateTestNodeID() - require.NoError(s.Add(nodeID1, nil, ids.Empty, stdmath.MaxInt64-1)) + require.NoError(s.Add(nodeID1, nil, ids.Empty, math.MaxInt64-1)) sampled, err = s.Sample(1) require.NoError(err) @@ -381,7 +381,7 @@ func TestSetString(t *testing.T) { s := NewSet() require.NoError(s.Add(nodeID0, nil, ids.Empty, 1)) - require.NoError(s.Add(nodeID1, nil, ids.Empty, stdmath.MaxInt64-1)) + require.NoError(s.Add(nodeID1, nil, ids.Empty, math.MaxInt64-1)) expected := "Validator Set: (Size = 2, Weight = 9223372036854775807)\n" + " Validator[0]: NodeID-111111111111111111116DBWJs, 1\n" + diff --git a/utils/sampler/weighted_test.go b/utils/sampler/weighted_test.go index f826e879f408..d67d86251c69 100644 --- a/utils/sampler/weighted_test.go +++ b/utils/sampler/weighted_test.go @@ -5,13 +5,12 @@ package sampler import ( "fmt" + "math" "testing" - stdmath "math" - "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/utils/math" + safemath "github.com/ava-labs/avalanchego/utils/math" ) var ( @@ -89,8 +88,8 @@ func TestAllWeighted(t *testing.T) { } func WeightedInitializeOverflowTest(t *testing.T, s Weighted) { - err := s.Initialize([]uint64{1, stdmath.MaxUint64}) - require.ErrorIs(t, err, math.ErrOverflow) + err := s.Initialize([]uint64{1, math.MaxUint64}) + require.ErrorIs(t, err, safemath.ErrOverflow) } func WeightedOutOfRangeTest(t *testing.T, s Weighted) { diff --git a/utils/sampler/weighted_without_replacement_test.go b/utils/sampler/weighted_without_replacement_test.go index b4a6d5e4d3cc..fe2dadaeb5c6 100644 --- a/utils/sampler/weighted_without_replacement_test.go +++ b/utils/sampler/weighted_without_replacement_test.go @@ -5,15 +5,14 @@ package sampler import ( "fmt" + "math" "testing" - stdmath "math" - "github.com/stretchr/testify/require" "golang.org/x/exp/slices" - "github.com/ava-labs/avalanchego/utils/math" + safemath "github.com/ava-labs/avalanchego/utils/math" ) var ( @@ -87,8 +86,8 @@ func WeightedWithoutReplacementInitializeOverflowTest( t *testing.T, s WeightedWithoutReplacement, ) { - err := s.Initialize([]uint64{1, stdmath.MaxUint64}) - require.ErrorIs(t, err, math.ErrOverflow) + err := s.Initialize([]uint64{1, math.MaxUint64}) + require.ErrorIs(t, err, safemath.ErrOverflow) } func WeightedWithoutReplacementOutOfRangeTest( diff --git a/vms/avm/states/state.go b/vms/avm/states/state.go index 1520fdd3a2ae..bf1ac3cde471 100644 --- a/vms/avm/states/state.go +++ b/vms/avm/states/state.go @@ -7,11 +7,10 @@ import ( "bytes" "errors" "fmt" + "math" "sync" "time" - stdmath "math" - "github.com/prometheus/client_golang/prometheus" "go.uber.org/zap" @@ -24,12 +23,13 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/choices" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/timer" "github.com/ava-labs/avalanchego/utils/wrappers" "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 ( @@ -715,7 +715,7 @@ func (s *state) Prune(lock sync.Locker, log logging.Logger) error { eta := timer.EstimateETA( startTime, progress-startProgress, - stdmath.MaxUint64-startProgress, + math.MaxUint64-startProgress, ) log.Info("committing state pruning", zap.Int("numPruned", numPruned), @@ -728,7 +728,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 := math.Min( + sleepDuration := safemath.Min( pruneCommitSleepMultiplier*pruneDuration, pruneCommitSleepCap, ) diff --git a/vms/avm/txs/executor/syntactic_verifier_test.go b/vms/avm/txs/executor/syntactic_verifier_test.go index 11a0c91864a1..34f1b27ebbcc 100644 --- a/vms/avm/txs/executor/syntactic_verifier_test.go +++ b/vms/avm/txs/executor/syntactic_verifier_test.go @@ -4,24 +4,24 @@ package executor import ( + "math" "strings" "testing" - stdmath "math" - "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/vms/avm/config" "github.com/ava-labs/avalanchego/vms/avm/fxs" "github.com/ava-labs/avalanchego/vms/avm/txs" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + + safemath "github.com/ava-labs/avalanchego/utils/math" ) var ( @@ -274,7 +274,7 @@ func TestSyntacticVerifierBaseTx(t *testing.T) { input1 := input input1.UTXOID.OutputIndex++ input1.In = &secp256k1fx.TransferInput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, Input: inputSigners, } @@ -292,7 +292,7 @@ func TestSyntacticVerifierBaseTx(t *testing.T) { }, } }, - err: math.ErrOverflow, + err: safemath.ErrOverflow, }, { name: "output overflow", @@ -305,7 +305,7 @@ func TestSyntacticVerifierBaseTx(t *testing.T) { output1 := output output1.Out = &secp256k1fx.TransferOutput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, OutputOwners: outputOwners, } @@ -322,7 +322,7 @@ func TestSyntacticVerifierBaseTx(t *testing.T) { Creds: creds, } }, - err: math.ErrOverflow, + err: safemath.ErrOverflow, }, { name: "insufficient funds", @@ -767,7 +767,7 @@ func TestSyntacticVerifierCreateAssetTx(t *testing.T) { input1 := input input1.UTXOID.OutputIndex++ input1.In = &secp256k1fx.TransferInput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, Input: inputSigners, } @@ -785,7 +785,7 @@ func TestSyntacticVerifierCreateAssetTx(t *testing.T) { }, } }, - err: math.ErrOverflow, + err: safemath.ErrOverflow, }, { name: "output overflow", @@ -798,7 +798,7 @@ func TestSyntacticVerifierCreateAssetTx(t *testing.T) { output1 := output output1.Out = &secp256k1fx.TransferOutput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, OutputOwners: outputOwners, } @@ -815,7 +815,7 @@ func TestSyntacticVerifierCreateAssetTx(t *testing.T) { Creds: creds, } }, - err: math.ErrOverflow, + err: safemath.ErrOverflow, }, { name: "insufficient funds", @@ -1286,7 +1286,7 @@ func TestSyntacticVerifierOperationTx(t *testing.T) { input1 := input input1.UTXOID.OutputIndex++ input1.In = &secp256k1fx.TransferInput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, Input: inputSigners, } @@ -1304,14 +1304,14 @@ func TestSyntacticVerifierOperationTx(t *testing.T) { }, } }, - err: math.ErrOverflow, + err: safemath.ErrOverflow, }, { name: "output overflow", txFunc: func() *txs.Tx { output := output output.Out = &secp256k1fx.TransferOutput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, OutputOwners: outputOwners, } @@ -1327,7 +1327,7 @@ func TestSyntacticVerifierOperationTx(t *testing.T) { Creds: creds, } }, - err: math.ErrOverflow, + err: safemath.ErrOverflow, }, { name: "insufficient funds", @@ -1773,7 +1773,7 @@ func TestSyntacticVerifierImportTx(t *testing.T) { input1 := input input1.UTXOID.OutputIndex++ input1.In = &secp256k1fx.TransferInput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, Input: inputSigners, } @@ -1791,14 +1791,14 @@ func TestSyntacticVerifierImportTx(t *testing.T) { }, } }, - err: math.ErrOverflow, + err: safemath.ErrOverflow, }, { name: "output overflow", txFunc: func() *txs.Tx { output := output output.Out = &secp256k1fx.TransferOutput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, OutputOwners: outputOwners, } @@ -1814,7 +1814,7 @@ func TestSyntacticVerifierImportTx(t *testing.T) { Creds: creds, } }, - err: math.ErrOverflow, + err: safemath.ErrOverflow, }, { name: "insufficient funds", @@ -2183,7 +2183,7 @@ func TestSyntacticVerifierExportTx(t *testing.T) { input1 := input input1.UTXOID.OutputIndex++ input1.In = &secp256k1fx.TransferInput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, Input: inputSigners, } @@ -2201,14 +2201,14 @@ func TestSyntacticVerifierExportTx(t *testing.T) { }, } }, - err: math.ErrOverflow, + err: safemath.ErrOverflow, }, { name: "output overflow", txFunc: func() *txs.Tx { output := output output.Out = &secp256k1fx.TransferOutput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, OutputOwners: outputOwners, } @@ -2224,7 +2224,7 @@ func TestSyntacticVerifierExportTx(t *testing.T) { Creds: creds, } }, - err: math.ErrOverflow, + err: safemath.ErrOverflow, }, { name: "insufficient funds", diff --git a/vms/platformvm/service.go b/vms/platformvm/service.go index 79003c471a85..a887ee72cb17 100644 --- a/vms/platformvm/service.go +++ b/vms/platformvm/service.go @@ -7,11 +7,11 @@ import ( "context" "errors" "fmt" + "math" "net/http" "time" stdjson "encoding/json" - stdmath "math" "go.uber.org/zap" @@ -29,7 +29,6 @@ import ( "github.com/ava-labs/avalanchego/utils/formatting" "github.com/ava-labs/avalanchego/utils/json" "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/utils/wrappers" "github.com/ava-labs/avalanchego/vms/components/avax" @@ -45,6 +44,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + safemath "github.com/ava-labs/avalanchego/utils/math" platformapi "github.com/ava-labs/avalanchego/vms/platformvm/api" ) @@ -244,16 +244,16 @@ utxoFor: switch out := utxo.Out.(type) { case *secp256k1fx.TransferOutput: if out.Locktime <= currentTime { - newBalance, err := math.Add64(unlockeds[assetID], out.Amount()) + newBalance, err := safemath.Add64(unlockeds[assetID], out.Amount()) if err != nil { - unlockeds[assetID] = stdmath.MaxUint64 + unlockeds[assetID] = math.MaxUint64 } else { unlockeds[assetID] = newBalance } } else { - newBalance, err := math.Add64(lockedNotStakeables[assetID], out.Amount()) + newBalance, err := safemath.Add64(lockedNotStakeables[assetID], out.Amount()) if err != nil { - lockedNotStakeables[assetID] = stdmath.MaxUint64 + lockedNotStakeables[assetID] = math.MaxUint64 } else { lockedNotStakeables[assetID] = newBalance } @@ -267,23 +267,23 @@ utxoFor: ) continue utxoFor case innerOut.Locktime > currentTime: - newBalance, err := math.Add64(lockedNotStakeables[assetID], out.Amount()) + newBalance, err := safemath.Add64(lockedNotStakeables[assetID], out.Amount()) if err != nil { - lockedNotStakeables[assetID] = stdmath.MaxUint64 + lockedNotStakeables[assetID] = math.MaxUint64 } else { lockedNotStakeables[assetID] = newBalance } case out.Locktime <= currentTime: - newBalance, err := math.Add64(unlockeds[assetID], out.Amount()) + newBalance, err := safemath.Add64(unlockeds[assetID], out.Amount()) if err != nil { - unlockeds[assetID] = stdmath.MaxUint64 + unlockeds[assetID] = math.MaxUint64 } else { unlockeds[assetID] = newBalance } default: - newBalance, err := math.Add64(lockedStakeables[assetID], out.Amount()) + newBalance, err := safemath.Add64(lockedStakeables[assetID], out.Amount()) if err != nil { - lockedStakeables[assetID] = stdmath.MaxUint64 + lockedStakeables[assetID] = math.MaxUint64 } else { lockedStakeables[assetID] = newBalance } @@ -297,17 +297,17 @@ utxoFor: balances := maps.Clone(lockedStakeables) for assetID, amount := range lockedNotStakeables { - newBalance, err := math.Add64(balances[assetID], amount) + newBalance, err := safemath.Add64(balances[assetID], amount) if err != nil { - balances[assetID] = stdmath.MaxUint64 + balances[assetID] = math.MaxUint64 } else { balances[assetID] = newBalance } } for assetID, amount := range unlockeds { - newBalance, err := math.Add64(balances[assetID], amount) + newBalance, err := safemath.Add64(balances[assetID], amount) if err != nil { - balances[assetID] = stdmath.MaxUint64 + balances[assetID] = math.MaxUint64 } else { balances[assetID] = newBalance } @@ -2762,9 +2762,9 @@ func getStakeHelper(tx *txs.Tx, addrs set.Set[ids.ShortID], totalAmountStaked ma } assetID := output.AssetID() - newAmount, err := math.Add64(totalAmountStaked[assetID], secpOut.Amt) + newAmount, err := safemath.Add64(totalAmountStaked[assetID], secpOut.Amt) if err != nil { - newAmount = stdmath.MaxUint64 + newAmount = math.MaxUint64 } totalAmountStaked[assetID] = newAmount diff --git a/vms/platformvm/state/state.go b/vms/platformvm/state/state.go index ca638daf0270..ca8c1ddd0768 100644 --- a/vms/platformvm/state/state.go +++ b/vms/platformvm/state/state.go @@ -7,11 +7,10 @@ import ( "context" "errors" "fmt" + "math" "sync" "time" - stdmath "math" - "github.com/google/btree" "go.uber.org/zap" @@ -34,7 +33,6 @@ import ( "github.com/ava-labs/avalanchego/utils/crypto/bls" "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/timer" "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/avalanchego/vms/components/avax" @@ -46,6 +44,8 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" + + safemath "github.com/ava-labs/avalanchego/utils/math" ) const ( @@ -400,14 +400,14 @@ type ValidatorWeightDiff struct { func (v *ValidatorWeightDiff) Add(negative bool, amount uint64) error { if v.Decrease == negative { var err error - v.Amount, err = math.Add64(v.Amount, amount) + v.Amount, err = safemath.Add64(v.Amount, amount) return err } if v.Amount > amount { v.Amount -= amount } else { - v.Amount = math.AbsDiff(v.Amount, amount) + v.Amount = safemath.AbsDiff(v.Amount, amount) v.Decrease = negative } return nil @@ -1268,11 +1268,11 @@ func applyWeightDiff( if weightDiff.Decrease { // The validator's weight was decreased at this block, so in the // prior block it was higher. - vdr.Weight, err = math.Add64(vdr.Weight, weightDiff.Amount) + vdr.Weight, err = safemath.Add64(vdr.Weight, weightDiff.Amount) } else { // The validator's weight was increased at this block, so in the // prior block it was lower. - vdr.Weight, err = math.Sub(vdr.Weight, weightDiff.Amount) + vdr.Weight, err = safemath.Sub(vdr.Weight, weightDiff.Amount) } if err != nil { return err @@ -1367,7 +1367,7 @@ func (s *state) syncGenesis(genesisBlk block.Block, genesis *genesis.Genesis) er stakeAmount, currentSupply, ) - newCurrentSupply, err := math.Add64(currentSupply, potentialReward) + newCurrentSupply, err := safemath.Add64(currentSupply, potentialReward) if err != nil { return err } @@ -2555,7 +2555,7 @@ func (s *state) PruneAndIndex(lock sync.Locker, log logging.Logger) error { eta := timer.EstimateETA( startTime, progress, - stdmath.MaxUint64, + math.MaxUint64, ) log.Info("committing state pruning and indexing", @@ -2570,7 +2570,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 := math.Min( + sleepDuration := safemath.Min( pruneCommitSleepMultiplier*pruneDuration, pruneCommitSleepCap, ) diff --git a/vms/platformvm/state/state_test.go b/vms/platformvm/state/state_test.go index 74d04b563155..d76505d0db85 100644 --- a/vms/platformvm/state/state_test.go +++ b/vms/platformvm/state/state_test.go @@ -5,11 +5,10 @@ package state import ( "context" + "math" "testing" "time" - stdmath "math" - "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" @@ -25,7 +24,6 @@ import ( "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/avalanchego/vms/components/avax" @@ -37,6 +35,8 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + + safemath "github.com/ava-labs/avalanchego/utils/math" ) var ( @@ -224,14 +224,14 @@ func TestValidatorWeightDiff(t *testing.T) { name: "decrease overflow", ops: []func(*ValidatorWeightDiff) error{ func(d *ValidatorWeightDiff) error { - return d.Add(true, stdmath.MaxUint64) + return d.Add(true, math.MaxUint64) }, func(d *ValidatorWeightDiff) error { return d.Add(true, 1) }, }, expected: &ValidatorWeightDiff{}, - expectedErr: math.ErrOverflow, + expectedErr: safemath.ErrOverflow, }, { name: "simple increase", @@ -253,14 +253,14 @@ func TestValidatorWeightDiff(t *testing.T) { name: "increase overflow", ops: []func(*ValidatorWeightDiff) error{ func(d *ValidatorWeightDiff) error { - return d.Add(false, stdmath.MaxUint64) + return d.Add(false, math.MaxUint64) }, func(d *ValidatorWeightDiff) error { return d.Add(false, 1) }, }, expected: &ValidatorWeightDiff{}, - expectedErr: math.ErrOverflow, + expectedErr: safemath.ErrOverflow, }, { name: "varied use", diff --git a/vms/platformvm/txs/add_permissionless_delegator_tx_test.go b/vms/platformvm/txs/add_permissionless_delegator_tx_test.go index 6fcf9df57a96..26e8d402bc84 100644 --- a/vms/platformvm/txs/add_permissionless_delegator_tx_test.go +++ b/vms/platformvm/txs/add_permissionless_delegator_tx_test.go @@ -5,10 +5,9 @@ package txs import ( "errors" + "math" "testing" - stdmath "math" - "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" @@ -17,13 +16,14 @@ import ( "github.com/ava-labs/avalanchego/snow" "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/units" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/vms/types" + + safemath "github.com/ava-labs/avalanchego/utils/math" ) var errCustom = errors.New("custom error") @@ -1443,7 +1443,7 @@ func TestAddPermissionlessDelegatorTxSyntacticVerify(t *testing.T) { ID: assetID, }, Out: &secp256k1fx.TransferOutput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, }, }, { @@ -1458,7 +1458,7 @@ func TestAddPermissionlessDelegatorTxSyntacticVerify(t *testing.T) { DelegationRewardsOwner: rewardsOwner, } }, - err: math.ErrOverflow, + err: safemath.ErrOverflow, }, { name: "weight mismatch", diff --git a/vms/platformvm/txs/add_permissionless_validator_tx_test.go b/vms/platformvm/txs/add_permissionless_validator_tx_test.go index 0ef718651254..79b1a64abd00 100644 --- a/vms/platformvm/txs/add_permissionless_validator_tx_test.go +++ b/vms/platformvm/txs/add_permissionless_validator_tx_test.go @@ -5,10 +5,9 @@ package txs import ( "encoding/hex" + "math" "testing" - stdmath "math" - "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" @@ -18,7 +17,6 @@ import ( "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/platformvm/fx" @@ -27,6 +25,8 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/vms/types" + + safemath "github.com/ava-labs/avalanchego/utils/math" ) func TestAddPermissionlessPrimaryValidator(t *testing.T) { @@ -1604,7 +1604,7 @@ func TestAddPermissionlessValidatorTxSyntacticVerify(t *testing.T) { ID: assetID, }, Out: &secp256k1fx.TransferOutput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, }, }, { @@ -1621,7 +1621,7 @@ func TestAddPermissionlessValidatorTxSyntacticVerify(t *testing.T) { DelegationShares: reward.PercentDenominator, } }, - err: math.ErrOverflow, + err: safemath.ErrOverflow, }, { name: "multiple staked assets", diff --git a/vms/platformvm/txs/executor/staker_tx_verification.go b/vms/platformvm/txs/executor/staker_tx_verification.go index 3f5a7e3afd90..f6c1ecd75bfa 100644 --- a/vms/platformvm/txs/executor/staker_tx_verification.go +++ b/vms/platformvm/txs/executor/staker_tx_verification.go @@ -6,16 +6,16 @@ package executor import ( "errors" "fmt" - - stdmath "math" + "math" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/txs" + + safemath "github.com/ava-labs/avalanchego/utils/math" ) var ( @@ -392,13 +392,13 @@ func verifyAddDelegatorTx( ) } - maximumWeight, err := math.Mul64(MaxValidatorWeightFactor, primaryNetworkValidator.Weight) + maximumWeight, err := safemath.Mul64(MaxValidatorWeightFactor, primaryNetworkValidator.Weight) if err != nil { return nil, ErrStakeOverflow } if backend.Config.IsApricotPhase3Activated(currentTimestamp) { - maximumWeight = math.Min(maximumWeight, backend.Config.MaxValidatorStake) + maximumWeight = safemath.Min(maximumWeight, backend.Config.MaxValidatorStake) } txID := sTx.ID() @@ -639,14 +639,14 @@ func verifyAddPermissionlessDelegatorTx( ) } - maximumWeight, err := math.Mul64( + maximumWeight, err := safemath.Mul64( uint64(delegatorRules.maxValidatorWeightFactor), validator.Weight, ) if err != nil { - maximumWeight = stdmath.MaxUint64 + maximumWeight = math.MaxUint64 } - maximumWeight = math.Min(maximumWeight, delegatorRules.maxValidatorStake) + maximumWeight = safemath.Min(maximumWeight, delegatorRules.maxValidatorStake) txID := sTx.ID() newStaker, err := state.NewPendingStaker(txID, tx) diff --git a/vms/platformvm/utxo/handler_test.go b/vms/platformvm/utxo/handler_test.go index 08784fe0e328..f74286987d32 100644 --- a/vms/platformvm/utxo/handler_test.go +++ b/vms/platformvm/utxo/handler_test.go @@ -4,23 +4,23 @@ package utxo import ( + "math" "testing" "time" - stdmath "math" - "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + + safemath "github.com/ava-labs/avalanchego/utils/math" ) var _ txs.UnsignedTx = (*dummyUnsignedTx)(nil) @@ -582,7 +582,7 @@ func TestVerifySpendUTXOs(t *testing.T) { { Asset: avax.Asset{ID: h.ctx.AVAXAssetID}, Out: &secp256k1fx.TransferOutput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, }, }, }, @@ -590,7 +590,7 @@ func TestVerifySpendUTXOs(t *testing.T) { &secp256k1fx.Credential{}, }, producedAmounts: map[ids.ID]uint64{}, - expectedErr: math.ErrOverflow, + expectedErr: safemath.ErrOverflow, }, { description: "attempted mint", @@ -660,7 +660,7 @@ func TestVerifySpendUTXOs(t *testing.T) { Out: &stakeable.LockOut{ Locktime: 1, TransferableOut: &secp256k1fx.TransferOutput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, }, }, }, @@ -669,7 +669,7 @@ func TestVerifySpendUTXOs(t *testing.T) { &secp256k1fx.Credential{}, }, producedAmounts: map[ids.ID]uint64{}, - expectedErr: math.ErrOverflow, + expectedErr: safemath.ErrOverflow, }, { description: "attempted mint through mixed locking (low then high)", @@ -701,7 +701,7 @@ func TestVerifySpendUTXOs(t *testing.T) { Out: &stakeable.LockOut{ Locktime: 1, TransferableOut: &secp256k1fx.TransferOutput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, }, }, }, @@ -734,7 +734,7 @@ func TestVerifySpendUTXOs(t *testing.T) { { Asset: avax.Asset{ID: h.ctx.AVAXAssetID}, Out: &secp256k1fx.TransferOutput{ - Amt: stdmath.MaxUint64, + Amt: math.MaxUint64, }, }, { diff --git a/x/sync/peer_tracker.go b/x/sync/peer_tracker.go index 97d47081d789..e1d471cc40ab 100644 --- a/x/sync/peer_tracker.go +++ b/x/sync/peer_tracker.go @@ -4,22 +4,22 @@ package sync import ( + "math" "math/rand" "sync" "time" "github.com/prometheus/client_golang/prometheus" - stdmath "math" - "go.uber.org/zap" "github.com/ava-labs/avalanchego/ids" "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/utils/wrappers" "github.com/ava-labs/avalanchego/version" + + safemath "github.com/ava-labs/avalanchego/utils/math" ) const ( @@ -38,7 +38,7 @@ const ( // information we track on a given peer type peerInfo struct { version *version.Application - bandwidth math.Averager + bandwidth safemath.Averager } // Tracks the bandwidth of responses coming from peers, @@ -55,8 +55,8 @@ type peerTracker struct { // Peers that we're connected to that responded to the last request they were sent. responsivePeers set.Set[ids.NodeID] // Max heap that contains the average bandwidth of peers. - bandwidthHeap math.AveragerHeap - averageBandwidth math.Averager + bandwidthHeap safemath.AveragerHeap + averageBandwidth safemath.Averager log logging.Logger numTrackedPeers prometheus.Gauge numResponsivePeers prometheus.Gauge @@ -72,8 +72,8 @@ func newPeerTracker( peers: make(map[ids.NodeID]*peerInfo), trackedPeers: make(set.Set[ids.NodeID]), responsivePeers: make(set.Set[ids.NodeID]), - bandwidthHeap: math.NewMaxAveragerHeap(), - averageBandwidth: math.NewAverager(0, bandwidthHalflife, time.Now()), + bandwidthHeap: safemath.NewMaxAveragerHeap(), + averageBandwidth: safemath.NewAverager(0, bandwidthHalflife, time.Now()), log: log, numTrackedPeers: prometheus.NewGauge( prometheus.GaugeOpts{ @@ -131,7 +131,7 @@ func (p *peerTracker) shouldTrackNewPeer() bool { // 5000 | 7.124576406741286e-218 // // In other words, the probability drops off extremely quickly. - newPeerProbability := stdmath.Exp(-float64(numResponsivePeers) * newPeerConnectFactor) + newPeerProbability := math.Exp(-float64(numResponsivePeers) * newPeerConnectFactor) return rand.Float64() < newPeerProbability // #nosec G404 } @@ -208,7 +208,7 @@ func (p *peerTracker) TrackBandwidth(nodeID ids.NodeID, bandwidth float64) { now := time.Now() if peer.bandwidth == nil { - peer.bandwidth = math.NewAverager(bandwidth, bandwidthHalflife, now) + peer.bandwidth = safemath.NewAverager(bandwidth, bandwidthHalflife, now) } else { peer.bandwidth.Observe(bandwidth, now) } From 1c1098bd3a3688ed2c15babe19c750b857379a29 Mon Sep 17 00:00:00 2001 From: dhrubabasu <7675102+dhrubabasu@users.noreply.github.com> Date: Wed, 11 Oct 2023 13:43:25 -0700 Subject: [PATCH 2/2] one more --- network/network.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/network/network.go b/network/network.go index 591987197824..212e867d1ac1 100644 --- a/network/network.go +++ b/network/network.go @@ -7,14 +7,13 @@ import ( "context" "errors" "fmt" + "math" "net" "strings" "sync" "sync/atomic" "time" - gomath "math" - "github.com/pires/go-proxyproto" "github.com/prometheus/client_golang/prometheus" @@ -37,11 +36,12 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "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/sampler" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/avalanchego/version" + + safemath "github.com/ava-labs/avalanchego/utils/math" ) const ( @@ -143,7 +143,7 @@ type network struct { // Call [onCloseCtxCancel] to cancel [onCloseCtx] during close() onCloseCtxCancel func() - sendFailRateCalculator math.Averager + sendFailRateCalculator safemath.Averager // Tracks which peers know about which peers gossipTracker peer.GossipTracker @@ -289,7 +289,7 @@ func NewNetwork( onCloseCtx: onCloseCtx, onCloseCtxCancel: cancel, - sendFailRateCalculator: math.NewSyncAverager(math.NewAverager( + sendFailRateCalculator: safemath.NewSyncAverager(safemath.NewAverager( 0, config.SendFailRateHalflife, time.Now(), @@ -1388,8 +1388,8 @@ func (n *network) NodeUptime(subnetID ids.ID) (UptimeResult, error) { } return UptimeResult{ - WeightedAveragePercentage: gomath.Abs(totalWeightedPercent / totalWeight), - RewardingStakePercentage: gomath.Abs(100 * rewardingStake / totalWeight), + WeightedAveragePercentage: math.Abs(totalWeightedPercent / totalWeight), + RewardingStakePercentage: math.Abs(100 * rewardingStake / totalWeight), }, nil }